自己的samrty模板引擎仿写简单版本(一)
通过上两篇文章,我们了解了smarty仿写的思路,今天了解自己的samrty模板引擎仿写简单版本(一)
实 例,有四个文件:
(1)模板文件:intro.htm,放在templates目录下;
(2)smarty类文件:MyMiniSmarty.class.php;
(3)编译后存放的文件:也就是MyMiniSmarty.class.php里 的$compile_file_path,放在templates_c目录下,这是程序生成的;
(4)访问测试效果的文件:intro.php
-------------文件1:intro.htm-----------目的,就是要将里面的{$title}和{$content}替换掉
<html>
<head><title>{$title}</title></head>
<body>
{$content}
</body>
</html>
----------文件2:MyMiniSmarty.class.php---------所有的操作都在这个类里完成了
<?php
class MyMiniSmarty
{
public $template_dir = "./templates/"; //模板文件路径
public $com_dir = "./templates_c/"; //指定模板文件被替换后的文件,的存放路径
public $tpl_vars = array(); //存放变量值public function assign($tpl_var, $val = null)
{ //分配,即就是给变量赋值
if ($tpl_var != '') {
$this->tpl_vars[$tpl_var] = $val;
}
}public function display($tpl_file)
{ //读取模板文件,并替换可以运行的php文件
$tpl_file_path = $this->template_dir . $tpl_file; //模板文件路径
$compile_file_path = $this->com_dir . $tpl_file . ".php"; //编译后的文件
if (!file_exists($tpl_file_path)) {
return false;
}
if (!file_exists($compile_file_path) || filemtime($tpl_file_path) > filemtime($compile_file_path)) { //编译文件不存在,或模板文件修改时间比编译文件修改时间新
$file_content = file_get_contents($tpl_file_path); //读取到文件内容
$pattern = array('/\{\s*\$([a-zA-z_][a-zA-z0-9_]*)\s*\}/i'); //需要替换的内容,根据intro.htm模板文件来写
$replace = array('<?php echo $this->tpl_vars["${1}"] ?>');
$new_str = preg_replace($pattern, $replace, $file_content);
file_put_contents($compile_file_path, $new_str); //新建或更新编译文件
}
include $compile_file_path; //读取编译文件,这就是我们实际看到的内容
}
}?>
------------文件4:intro.php-----访问这个文件,即可读取到相应的内容
<?php
//使用MyMiniSmarty.class.php类
require_once('MyMiniSmarty.class.php');
$mysmarty = new MyMiniSmarty();
$mysmarty->assign("title","文档标题");
$mysmarty->assign("content","文档内容");
$mysmarty->display("intro.htm");
?>
相关文章:
第一个沙发给自己.