PHP smarty模板技术


模板引擎技术的核心思想是 数据和界面显示分离


//引入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将数据分配给要传入的模板中的标签变量

$smarty->assign("var1","hello.world!");
//指定用哪个模板显示
$smarty->display("hello.tpl");

1、读取模板文件
模板文件
模板中要显示的动态数据用smarty标签来代替
<html>
<head><title> {$title}</title></head>
<body>  {$content}  </body>
</html>

2、把模板文件替换成可以运行的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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值