smarty模板
功能:php和html分离=>controller和view
eg:
<p>{$str}</p> => <p><?php echo $str; ?></p>
把模板经过编译/解析(compile)变为后者
mini.class.php
<?php
/*smarty模板*/
class mini{
// compile编译;template模板;编译是从高语言,编到低语言
//模板和编译后的文件 地址
public $template_dir='';
public $compile_dir='';
//接收外面变量
public $arr;
//编译方法过程:读取模板内容-》编译-》保存
/*
parm $template 模板文件名
return 编译文件地址*/
public function compile($template){
$temp=$this->template_dir.'/'.$template;
$comp=$this->compile_dir.'/'.$template.'.php';
/*若模板没改动就用之前编译过的html;模板时间且小于编译时间*/
if (file_exists($comp)&& filemtime($temp)<filemtime($comp)) {
return $comp;
}
//读取模板的内容
$res=file_get_contents($temp);
//编译...{-->>>{$...$str-->>>$this->arr['str'] (str是例子)
$res=str_replace('{$','<?php echo $this->arr[\'',$res);
//error替换反了错,高到低,所以用<?php替换 {}
$res=str_replace('}','\'] ;?>', $res);
//保存,comp是编译文件的路径
file_put_contents($comp,$res);
return $comp;
}
public function display($template){
$path= $this->compile($template);
include($path);
}
public function assign($k,$v){
$this->arr[$k]=$v;
return $this->arr;
}
}
?>调用 php
<?php
require './mini.class.php';
//变量
$str='hello,this is my best day~';
//调用模板转换
$mini=new mini();
//error Undefined variable: template_dir 写错成$mini->$template_dir
$mini->template_dir='./template';
$mini->compile_dir='./compile';
/*引入编译后的文件地址
$path=$mini->compile('temp.html');
include($path);
希望能自动引入*/
//$mini->display('temp.html');但这样不能引入,因为变量是全局,而display用不了外面的。所以变量需要放到类属性里
$mini->assign('str',$str);
$mini->display('temp.html');
?>smarty是一个类,要使用必先引入类并实例化;assign赋值;display编译自动include
smarty之不好
1写模板浪费时间
2变量赋值两次
本文介绍了一个简单的PHP模板引擎实现——Smarty。通过Smarty可以实现PHP与HTML的分离,提高开发效率。文章详细解释了Smarty的工作原理,包括如何编译模板、传递变量及显示编译后的页面。
1067

被折叠的 条评论
为什么被折叠?



