PHP自定义模板引擎

类文件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');
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,099评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,964评论 25 709
  • 太阳是你的 月亮也是你的 不必为别人无心的语言 黯然伤神 春风是你的 秋月也是你的 不必为了别人的评价 而刻意表现...
    南风鱼儿阅读 196评论 0 1
  • 我一直 在世间寻找 却很少遇见 这遇见的很少 让我充满希望 又充满质疑 我到底应该拥抱生活 还是应该远离人类 或者...
    陈皮朵娃阅读 287评论 0 0
  • 今天我将用一个故事来诠释下何谓鱼塘营销,鱼塘营销背后真正的手段是什么。请大家花一分钟的时间看完之后,相信你们一定会...
    洪兴会阅读 1,194评论 0 0