自定义模板引擎

类文件my/config.class.php
<?php
class Smarty
{
// 属性
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
<!DOCTYPE html >
< html lang= "en" >
< head >
< meta charset= "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 = new smarty ();
$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 = new smarty ();
$title = ' 只有学习让我快乐 ' ;
$content = ' 我爱 PHP' ;
$aa = ' 我爱 PHP' ;
// 向模板中分配变量
$smarty -> assign ( 'hello' , $title );
$smarty -> assign ( 'content' , $content );
$smarty -> assign ( 'haha' , $aa );
$smarty -> display ( '01.html' );



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值