Home  >  Article  >  Backend Development  >  初识PHP的smarty模板发动机

初识PHP的smarty模板发动机

WBOY
WBOYOriginal
2016-06-13 13:03:02763browse

初识PHP的smarty模板引擎
php是 嵌入式HTML脚本语言,为了将HTML和php代码分离,即所谓的逻辑层和表现层,这就是模板引擎的目的。为了达到该目的 模板引擎需具备的功能有:1.存储变量;2.读取模板文件;3.结合前两个生成输出。Code如下:

test01.php


$name='xiaoshenge';

?>

test02.php



test



name=





test03.php


include'test01.php';

include'test02.php;

?>

当然这里只是简单的模拟如何实现php模板引擎的功能,在php开源社区里著名的smarty就是封装了上面的功能。保存数据->加载模板->编译生成输出文件。有关 smarty的应用具体参考手册,这里只是解释其功能原理。

BTW:记录一下smarty缓存遇到的问题。

如果开启smarty缓存,第一次执行时会将其编译好的输出文件保存到cache目录中,在程序中通过smarty的is_cache()函数检测其 cache文件是否过期,若过期会更新缓存,如果没有过期会自动调用cache文件,省去编译的过程。检测cache过期是看模板文件是否在指定的生命周期内是否更改,这里的更改是是通过检测文件的最近修改时间实现的,不是通过检测模板文件内容。
   阻止一个模板文件的 整篇被缓存 :
index.php:

require('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;

function smarty_block_dynamic($param, $content, &$smarty) {
return $content;
}
$smarty->register_block('dynamic', 'smarty_block_dynamic', false);

$smarty->display('index.tpl');


index.tpl:

Page created: {"0"|date_format:"%D %H:%M:%S"}

{dynamic}

Now is: {"0"|date_format:"%D %H:%M:%S"}

... do other stuff ...

{/dynamic}
当重新加载这个页面,你将会注意到这两个日期不同。一个是“动态“,一个是“静态”。你能够在{dynamic}...{/dynamic}之间作任何事情,并且保证它将不会像剩下的页面一样被缓存。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn