初会smarty

©Smarty 可以实现代码分离 php 和 html 分离。 逻辑代码和html前端代码分离,便于修改,维护,扩展。

例子:php代码页面include html页面,不要混杂在一个文件内。html内 php只 echo数据,这个是mvc。

smarty是把php和html完全分离,html 里看不到php. 

html内是{$变量},用echo也可以,原生php输出快。WordPress,CI框架。

Smarty是模板,ecshop 改进的Smarty. tp自己的模板,织梦自己的模板。工作中未必用到smarty,模板的使用模式。原理相同。

© 2.6 php 4.X.X 3.1.13 新版本

©模板代码分离的实质是 把常规的嵌入到html里的代码标签 <?php ...;?> 翻译成 { } [str_replace] 

  把html文件生成另一个php文件,然后可以include到需要引用的php逻辑代码下,组成完整的页面代码。

  注意外面的变量的作用域,是否能影响到类内,模板内

  技巧,类内定义属性 数组  数组[key] = value 来存储 外部传入的变量值

 翻译就是 <?php $this->array[\' '.  变量名 . '\'];?>

$smarty的工作流程:
1:把需要显示的全局变量,赋值,塞到对象内部的属性上,一个数组里
2:编译模板,把{$标签},解析成相应的php echo 代码
3:引入编译后的PHP文件

使用smarty的步骤:
1:smarty是一个类,要使用,需先引入并实例化
2:assign赋值
3:display [编译到输出]

©

<?php

smarty流程:
1:引入smarty
2:实例化
3:配置[最基本的要配置模板目录,和编译目录]
***/



// 引入smarty
require('../Smarty3/libs/Smarty.class.php');

// 实例化
$smarty = new Smarty();

// print_r($smarty);

// 配置
$smarty->template_dir = './temp';
$smarty->compile_dir = './comp';


$title = '两会召开中';
$content = '提案特别多,听说房子要涨价';

// 赋值
$smarty->assign('xxx',$title);
$smarty->assign('content',$content);


$smarty->display('news.html');

?>

smarty标签变量,来源于3个部分
1: 是php中assign分配的变量
2: smarty的系统保留变量
3: 从配置文件读取到的配置变量

©

<?php
// 引入smarty
require('../Smarty3/libs/Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir = './temp';
$smarty->compile_dir = './comp';
$smarty->config_dir = './conf';



/*
    这是smarty模板assign的源码

    如果第1个参数是数组的话, 
    效果是把此数组的每个值,赋到以相应的键为名称的标签上去


    public function assign($tpl_var, $value = null, $nocache = false)
    {
        if (is_array($tpl_var)) {
            foreach ($tpl_var as $_key => $_val) {
                if ($_key != '') {
                    $this->tpl_vars[$_key] = new Smarty_variable($_val, $nocache);
                }
            }
        } else {
            if ($tpl_var != '') {
                $this->tpl_vars[$tpl_var] = new Smarty_variable($value, $nocache);
            }
        }

        return $this;
    }

*/
$user = array('name'=>'刘备','age'=>'28');
$smarty->assign($user);
/*
等于
$smarty->assign('name','刘备');
$smarty->assign('age',''28);
*/
?>

// 连着往某一个标签赋多个值时,我们可以用append, append是附加,追加的意思
$smarty->append('stu','李四'); // 这1步,_tpl_var['stu'][] = '李四';
$smarty->append('stu','王五'); // 这1步,_tpl_var['stu'][] = '王五';
// 也就是,把append到一个标签里变量,都一个数组里

111111

原文地址:https://www.cnblogs.com/zy2012/p/2944767.html