编辑一个小的smarty类

首先先建立两个文件夹,一个temp,存储编译前的文件,一个comp,存储编译后的文件,编译前的文件使用{$title}代替<?php echo $title; ?>,然后将前者编译成后者再解析,解析后存储在comp文件夹中

定义一个解析类smarty.class.php

<?php

//定义一个简单的smarty类,来编译html文件
class mini{
    public $temp_uri='';//模板文件所在的位置
    public $comp_uri='';//模板编译后存放的位置
    public $_var=array();//变量数组

    public function assign($key,$value){
        $this->_var[$key]=$value;
    }

    public function display($temp){//封装
        $uri=$this->complie($temp);
        require($uri);
    }
    /*
    String $tempplate模板文件名
    return String 
    */
    public function complie($temp){
        //读出模板的内容
        $te=$this->temp_uri.'/'.$temp;//编译前的文件
        $source=file_get_contents($te);
        $comp='./comp/'.$temp.'.php';

        //判断这个文件是否是存在
        if(file_exists($comp)&&filemtime($comp)>filemtime($te)){//编译后文件存在并且还要这个保存要比编译前的文件保存的早
            return $comp;

        }

        $source=str_replace('{$', '<?php echo $this->_var[\'', $source);
        $source=str_replace('}', '\'];?>', $source);
        
        var_dump(file_put_contents($comp,$source));
        return $comp;
    }
}

?>

 在temp目录下的编译前文件01temp.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{$title}</title>
</head>
<body>
    下面是php模板的内容<br/>
    {$content}
</body>
</html>

控制页面01.php

<?php

require('./smarty.class.php');
$title='商城';
$content='这是我的商城哦';
$smarty=new mini();
$smarty->temp_uri='./temp';
$smarty->comp_uri='./comp';
// $smarty->complie('01temp.html');
$smarty->assign('title',$title);
$smarty->assign('content',$content);
$smarty->display('01temp.html');
?>

 运行01.php生成在comp目录下的编译后文件01temp.html.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo $this->_var['title'];?></title>
</head>
<body>
    下面是php模板的内容<br/>
    <?php echo $this->_var['content'];?>
</body>
</html>

达到正确的结果

转载于:https://www.cnblogs.com/lzzhuany/p/4827739.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值