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 混编文件。