自定义模板引擎

来源:互联网 发布:苹果cms采集规则教程 编辑:程序博客网 时间:2024/06/15 22:37
类文件my/config.class.php
<?php
classSmarty
{
//属性
public$arr;
//方法 向模板中分配变量
public function assign($name,$value)
{
$this->arr[$name]=$value;
}
//调用模板
public function display($temp)
{
//模板文件路径
$path="templaces/";
//编译文件路径
$com="templaces_c/";
//模板文件名字
$comfile=$com.$temp.'.php';
/*1.如果编译文件不存在需要重新生成编译文件
2.如果模板文件发生了改变,需要重新生成编译文件
*/
if(!file_exists($comfile)||filectime($path.$temp)>filectime($comfile)){//判断模板文件是否存在(如果文件不存在就创建)
//获取模板源代码
$str=file_get_contents($path.$temp);
//查找模板中的变量(模糊匹配)
//正则----$reg = '/\{\s*\$([a-zA-Z_]\w*)\s*\}/';
$reg='/\{\s*\$([a-zA-Z_]\w*)\s*\}/';
/*替换成<?php echo $this->arr['']?> 模式单元双引号加\\*/
$place="<?php echo\$this->arr['\\1'] ?>";
//获取替换后的代码
$html=preg_replace($reg,$place,$str);
//编译文件(模板文件.php)
file_put_contents($comfile,$html);
}
include_once$comfile;
}

}
模板文件my/templaces
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Title</title>
<body>
<!--smarty模板引擎 引用变量:{变量}-->
{$title} {$hello}
</body>
</html>
<!--模板文件(可以是任何后缀)-->
引用文件my/templaces_c
<?php
header("Content-type:text/html;charset=utf-8");
/**
* Created by PhpStorm.
* User: lanouhn
* Date: 2017/10/12
* Time: 11:46
*/
include_once'config/smarty.class.php';
$smarty=newsmarty();
$title='只有学习让我快乐';
$content='我爱PHP';
$aa='我爱PHP';
//向模板中分配变量
$smarty->assign('hello',$title);
$smarty->assign('content',$content);
$smarty->assign('haha',$aa);
$smarty->display('01.html');
编译文件0.1.php
<?php
header("Content-type:text/html;charset=utf-8");
/**
* Created by PhpStorm.
* User: lanouhn
* Date: 2017/10/12
* Time: 11:46
*/
include_once'config/smarty.class.php';
$smarty=newsmarty();
$title='只有学习让我快乐';
$content='我爱PHP';
$aa='我爱PHP';
//向模板中分配变量
$smarty->assign('hello',$title);
$smarty->assign('content',$content);
$smarty->assign('haha',$aa);
$smarty->display('01.html');



原创粉丝点击