简单的山寨Smarty.

本文介绍了一个简单的Smarty模板引擎实现过程,包括定义MyMiniSmarty类、设置模板和编译目录、编写assign和display方法等关键步骤。

先编写一个MyMiniSmarty的类

<?php
class MiniSmarty {
//模板文件路径
var $template_dir="./templates/";
//指定一个模板文件被替换后的文件
var $complie_dir="./templates_c/";
//存放变量
var $tpl_vars=array();

//模拟两个主要的方法;
function assign($tpl_var,$val=NULL){
if($tpl_var!=''){
$this->tpl_vars[$tpl_var]=$val;
}
}
//读取模板
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);
}
echo 'ok';
include_once $complie_file_path;
}
}
?>

然后在根目录分别创建模板文件夹templates和存放编译后的文件夹templates_c

在templates文件夹中新建一个模板test.tpl

代码如下:

<head>
<title>samrty研究2</title>
</head>
<body>
<h1>{$title}</h1>
<p>helloword^-^</p>
</body>

在index.php文件夹调用MyMiniSmarty类.文件代码如下:

<?php
require_once 'MyMiniSmarty.php';

$test=new MiniSmarty;
$test->assign("title","my first smarty test");

$test->display(test.tpl');
?>

 

这样一个简单的smarty引擎就完成啦.^-^.

转载于:https://www.cnblogs.com/dzero/archive/2013/03/24/2979688.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值