封装PHP模板引擎Smarty类

1首先将文件进行分类:

1. 模板文件夹:view
2. 混编文件夹:viewc
3. Smarty文件:smarty.class.php
4. 入口文件:index.php

2代码部分

Smarty.class.php代码如下:

<?php
/**
 * User: Jokenzhang
 */
class Smarty{
    public $template_dir = './view/';//默认模板目录
    public $complie_dir = './viewc/';//默认混编目录
    private $com_val = array();
    //赋值函数
    public function assgin($k,$v){
        $this->com_val[$k] = $v;
    }
    public function display($tal){      //封装编译函数
        require $this->complie($tal);
    }
    /*
     *
     * @param $tal string 模板的名字
     */
    private function complie($tal){
        $complate_file = $this->complie_dir.$tal.'.php';//拼接模板地址
        $template_file = $this->template_dir.$tal;//拼接混编地址
        if(is_file($complate_file) && filemtime($complate_file) < filemtime($template_file)){
            return  $complate_file;
        }else{
            $str = file_get_contents($template_file);
            $str = str_replace('{$','<?php echo $this->com_val[\'',$str);//替换左大括号
            $str = str_replace('}','\'] ?>',$str);//替换右大括号
            file_put_contents($complate_file,$str);//写入混编文件
            return  $complate_file;//包含混编文件
        }
    }
}

index.php代码如下

<?php
/**
 * User: Jokenzhang
 */
require './Smarty.class.php';
$sa = new Smarty();
$sa->complie_dir = './viewc/';//更改混编路径
$sa->template_dir = './view/';//更改模板路径
$sa->assgin('name', 'tom');
$sa->assgin('age', '30');
$sa->assgin('height', '29');
$sa->display('temp_file.html');

complate.html 代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
{$name}
{$age}
{$height}
</body>
</html>

运行index.php文件浏览器会显示响应的数据,并且会在 viewc 文件夹中生成temp_file.html.php 混编文件。

感谢支持,点击进入头条号

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值