模板引擎技术的核心思想是
数据和界面显示分离
//引入smarty文件
require_once './libs/smarty.class.php';
$smarty=new smarty;
$smarty->caching=false;//是否使用缓存
$smarty->template_dir="./templates";
$smarty->compile_dir="./templates_c";
$smarty->left_delimiter="<{";
$smarty->right_delimiter="}>";
//把$res分配到smarty对象
//assign将数据分配给要传入的模板中的标签变量
//assign将数据分配给要传入的模板中的标签变量
$smarty->assign("var1","hello.world!");
//指定用哪个模板显示
$smarty->display("hello.tpl");
1、读取模板文件
模板文件
模板中要显示的动态数据用smarty标签来代替
<html>
<head><title>
{$title}</title></head>
<body>
{$content}
</body>
</html>
2、把模板文件替换成可以运行的php文件
替换后的文件
模板通过正则替换,将标签变量替换成输出真实数据的php语句
模板通过正则替换,将标签变量替换成输出真实数据的php语句
<html>
<head><title>
<?php echo $this->tpl_vars['title']?></title></head>
<body>
<?php echo $this->tpl_vars['content']?></body>
</html>
我们通过编写MyMiniSmarty来讲解smarty模板技术的核心原理
intro.php
<?php
//使用MyMiniSmarty.class.php
require_once 'MyMiniSmarty.class.php';
$mysmarty=new MyMiniSmarty;
$mysmarty->assign("title","我的第一个文件title");
$mysmarty->assign("content","我的第一个文件内容");
$mysmarty->display("intro.tpl");
?>
MyMiniSmarty.class.php
<?php
class MyMiniSmarty{
//我们模板文件的路径
var $template_dir="./templates/";
//这里我们需要指定一个模板文件被替换后的文件 格式com_对应的tpl.php
var $complie_dir="./templates_c/";
//存放变量值
var $tpl_vars=array();
//这里我们主要模拟两个方法
function assign($tpl_var,$val=null){
if($tpl_var!=''){
$this->tpl_vars[$tpl_var]=$val;
}
}
//这里编写display
function display($tpl_file){
//读取这个模板文件->替换可以运行php(编译后文件)
$tpl_file_path=$this->template_dir.$tpl_file;
$complie_file_path=$this->complie_dir."com_".$tpl_file.".php";
//判读文件存在否
if(!file_exists($tpl_file_path)){
return false;
}
//有没有必要每次都去生成一个编译后的文件
//当模板编译后的文件存在同时模板文件的修改时间小于模板编译文件的时候就不用再编译了,这样可以提高效率
//当模板编译后的文件存在同时模板文件的修改时间小于模板编译文件的时候就不用再编译了,这样可以提高效率
if(!file_exists($complie_file_path) || filemtime($tpl_file_path)>filemtime($complie_file_path)){
$tpl_file_con=file_get_contents($tpl_file_path);
$pattern=array(
'/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/i'
);
$replace=array(
'<?php echo $this->tpl_vars["${1}"]?>'
);
$new_str=preg_replace($pattern,$replace,$tpl_file_con);
file_put_contents($complie_file_path,$new_str);
}
include $complie_file_path;
}
}
?>
intro.tpl
<html>
<head><title>{$title}</title></head>
<body>
{$content}
</body>
</html>