他的流程就是
请求
-> b.php文件中 绑定变量 ,展示模板
-> smarty.php文件中的步骤
1 读取静态文件 a.html中的所有内容
2 正则替换这个静态文件a.html上的特定字符,如{$title}
3 替换完之后再把替换后的内容,生成为一个文件a.html.php(用作前端展示的)
4然后再包含这个新生成的文件
-> 展示这个替换过后的页面
未处理过的前端页面
a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{$title}</title>
</head>
<body>
{$contens}
</body>
</html>
开始展示模板
b.php
<?php
include './smarty.php';
$smarty = new Smarty;
$tit = '标题';// 数据库的数据
$contens = '内容';// 数据库的数据
$smarty->assign('title', $tit);
$smarty->assign('contens', $contens);
$smarty->display('a.html');
smarty 类的方法
smarty.php
<?php
class Smarty {
private $vars = array();
/**
* 分配变量
* @param [type] $varname [description]
* @param [type] $varvalue [description]
* @return [type] [description]
*/
public function assign($varname, $varvalue) {
$this->vars[$varname] = $varvalue;
}
/**
* 显示模板
* @param [type] $tplname [description]
* @return [type] [description]
*/
public function display($tplname) {
$html = file_get_contents($tplname);//打开这个文件,这个文件是 a.html
$zhengZeTiaoJian = '/\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}/';// 正则替换变量的条件
$rep = "<?php echo \$this->vars['\\1']; ?>";//如果是\\1的话就是是否有$,\\0和$0代表完整的模式匹配文本,当然是要配合preg_replace() 这个函数来做
$newhtml = preg_replace($zhengZeTiaoJian, $rep, $html);//如果html这个页面有(变量),就把他写进\\1里面,\\1代表是是否有$,有就去除,如果是\\0的话就是全部匹配
file_put_contents($tplname.".php", $newhtml);//把文件存进去
include $tplname.'.php';//显示这个文件
}
}
生成的模板文件如下:
a.html.php 这个文件,就是用来展示给用户看的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo $this->vars['title']; ?></title>
</head>
<body>
<?php echo $this->vars['contens']; ?>
</body>
</html>