自定义Smarty(三)

来源:互联网 发布:redis可视化工具 知乎 编辑:程序博客网 时间:2024/06/05 16:46

新建一个模板文件夹(view, template),和编译文件夹(view_c,template_c),用来存放对应的文件


Smarty代码:

<?phpclass Smarty{private $tpl_var = array();public $template_dir = './template/';public $templatec_dir = './template_c/';public function assign($k, $v){$this->tpl_var[$k] = $v;}public function display($tpl){$this->compile($tpl);}private function compile($tpl){$tpl_path = $this->template_dir . $tpl;$compile_path = $this->templatec_dir . $tpl . '.php';//如果文件存在并且创建混编文件大于模板修改的时间if(file_exists($compile_path) && filemtime($compile_path) > filemtime($tpl_path)){require $compile_path;} else {//取出demo.html文档中的内容$str = file_get_contents($tpl_path);//替换定界符的代码,在oop中取值的方法,注意面向过程不同$str = str_replace('{', '<?php echo $this->tpl_var["', $str);$str = str_replace('}', '"]; ?>', $str);//将这个文件写入demo.html.php,demo.html.php为混编文件file_put_contents($compile_path, $str);require $compile_path;}  }}

使用smarty

<?phprequire './Smarty/Smarty.class.php';$smarty = new Smarty();$smarty->assign('title', '锄禾');$smarty->assign('content', '锄禾日当午,汗滴禾下土。谁知盘中餐,粒粒皆辛苦。');$smarty->display('demo.html');

原模板文件:

<!doctype html><html lang="en"> <head><meta charset="UTF-8"><meta name="Generator" content="EditPlus®">  <meta name="Author" content="">  <meta name="Keywords" content="">  <meta name="Description" content="">  <title>Document</title></head><body>{title} <br/>{content} <hr/></body></html>


原创粉丝点击