smarty中的缓存问题

来源:互联网 发布:华泰证券交易软件 mac 编辑:程序博客网 时间:2024/05/01 00:36
 Smarty提供了强大的缓存功能。但有时候我们不希望整篇文档都被缓存,而是选择的缓存某一部分内容或某一部分不被缓存,Smarty提供了三种方法实现:
看下面的例子
模块文件test.html:
使用insert函数使模板一部分不被缓存
<br><{$file}><{$str}><br>
<div>这里是insert更新部分<{insert name="get_current_time"}></div>
<br>
使用register_function阻止内容从缓存输出
<div>这里是register_function函数更新部分< {current_time}></div>
<br>
使用register_block使用整篇页面的某一块区域不被缓存
<div>
Page created: <{"0"|date_format:"%D %H:%M:%S"}>
<{dynamic}>
Now is:<{"0"|date_format:"%D %H:%M:%S"}>
<{/dynamic}>
</div>
test.php:
<?php
include_once("sm_config.php");
$smarty->caching = true;
function insert_get_current_time() {
return date("Y-m-d H:m:s");
}
function smarty_function_current_time($params, $smarty) {
return date("Y-m-d H:m:s");
}
function smarty_block_dynamic($param, $content, $smarty) {
return $content;
}
if (!$smarty->is_cached("test.html")) {
$file = "缓存内容:";
$str = "Hello World!";
}
$smarty->register_function("current_time", "smarty_function_current_time", false);
$smarty->register_block("dynamic", "smarty_block_dynamic", false);
$smarty->assign("str",$str);
$smarty->assign("file", $file);
$smarty->display("test.html");
?>
注意每次刷新都会更新时间,这部分就是不被缓存的,其实变量可修改内容后再刷新,也不会变化,因为已经被缓存过了。
总结:
insert非常方便,register_function和register_block更灵活,但register_function要在 is_cached()前完成注册函数,不然会因找不到注册函数而导致smarty错误。
原创粉丝点击