PHP自定义Smarty模板引擎类高洛峰细说PHP
smarty模板引擎类简单工作原理

站在用户的角度思考问题,与客户深入沟通,找到永新网站设计与永新网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站建设、成都做网站、企业官网、英文网站、手机端网站、网站推广、空间域名、网页空间、企业邮箱。业务覆盖永新地区。
利用Smarty 模板引擎类对模板文件中的变量进行编译,编译过程其实就是利用正则表达式翻译成PHP文件。例如 模板文件中{$title}利用正则表达式找到并替换成 vars['title'];?>
自定义 Smarty 模板引擎类 smarty.class.php页面
vars[$name]=$value;
}
//加载指定的模板 并显示
//有一个参数是模板的文件名
public function display($tplname){
$comfile = "./comps/".$tplname."_com.php";
$tplname = "./templates/".$tplname;
//编译文件不存在 或者模板文件有变化 才需要编译
if(!file_exists($comfile) || filemtime($tplname)>filemtime($comfile)){
$html = file_get_contents($tplname);
//要替换的部分{title}
$reg = '/\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}/';
//变量正则表达式[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
//替换后的部分vars['title'];?>
$rep = "vars['\\1'];?>";
$newhtml = preg_replace($reg, $rep, $html);
file_put_contents($comfile, $newhtml);
}
include $comfile;
}
}调用模板页面 index.php
assign('title', $title);
$smarty->assign('content', $content);
var_dump($smarty);
//加载指定的模板 并显示
$smarty->display('c.php');模板文件页 c.php页面
{$title} {$title}
{$content}
输出结果
object(Smarty)[1] private 'vars' => array (size=2) 'title' => string 'This is a test' (length=14) 'content' => string 'This is content ......' (length=22) This is a test This is content ......
文章名称:PHP自定义Smarty模板引擎类高洛峰细说PHP
文章URL:http://www.jxjierui.cn/article/iiiico.html


咨询
建站咨询
