Smarty

模板(html+css)引擎技术之一

可以使得“php代码”与“html代码”分离的技术都称为模板引擎技术。

image-20200114163331220

模板引擎实际上是一个类

示例

目录

1
2
3
4
5
6
7
view
--02.html
--03.html
view_c
--02.html.php
--03.html.php
MiniSmarty.class.php

02.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>新建网页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />

<script type="text/javascript">
</script>

<style type="text/css">
</style>
</head>
<body>
<div>{$title}</div>
<div>{$content}</div>
</body>
</html>

MiniSmarty.class.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
//模板引擎类
class MiniSmarty{
public $template_dir = "./view/";//模板目录
public $templatec_dir = "./view_c/";//编译文件目录

//给该类声明属性,用于存储外部的变量信息
public $tpl_var = array();
//把外部变量设置为类内部属性的一部分
function assign($k, $v){
$this -> tpl_var[$k] = $v;
}

function display($tpl){
$n = $this -> compile($tpl);
require $n;
}

//"编译"模板文件( {}标记替换为php标记 )
function compile($tpl){
$tpl_file = $this->template_dir.$tpl;
$com_file = $this->templatec_dir.$tpl.".php";
//走“已经生成”的混编文件
//① 该混编文件必须存在
//② 混编文件的修改时间 大于 模板文件的修改时间
if(file_exists($com_file) && filemtime($com_file) > filemtime($tpl_file)){
return $com_file;
}

//获得模板文件内部具体的模板内容
$cont = file_get_contents($tpl_file);

//替换:{ ----> < ?php echo
//替换:{ ----> < ?php echo $this->tpl_var['
$cont = str_replace("{\$","<?php echo \$this->tpl_var['",$cont);

//替换: }-----> ; ? >
//替换: }-----> ']; ? >
$cont = str_replace("}","']; ?>",$cont);

//echo $cont;
//把生成好的编译内容(php+html混编内容)放入一个文件里边
file_put_contents($com_file,$cont);

//引入混编文件
return $com_file;

}
}

02.html.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>新建网页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />

<script type="text/javascript">
</script>

<style type="text/css">
</style>
</head>
<body>
<div><?php echo $this->tpl_var['title']; ?></div>
<div><?php echo $this->tpl_var['content']; ?></div>
</body>
</html>

Smarty模板引擎

对php里边的超级全局数组变量信息的使用

$smarty为smarty的保留变量

1
<div>{$age}</div>或者<div>{$smarty.get.age}</div>//get传参的age变量,get代表超全局数组$_GET

变量调剂器

smarty本身不支持我们在模板中使用php函数,其把函数给封装了一下,这个封装的函数就是smarty的变量调剂器。