smarty模板引擎中控制部分数据不被缓存的方法: 主要有三种方法
1、使用insert函数使模板的一部分不被缓存 index.tpl: <div>{insert name=]get_current_time]}</div>
index.php function insert_get_current_time(){ return date([Y-m-d H:m:s]); }
$smarty=new smarty(); $smarty->caching = true; if(!$smarty->is_cached('index.tpl')){ ……. } $smarty->display(‘index.tpl’);
注解: 定义一个函数,函数名格式为:inser_name(array $params, object &$smarty), 函数参数可选的,如果在模板的insert方法中需要加入其他属性,就会作为数组传递给用户定义的函数。 如:{insert name=’get_current_time’ local=’zh’} 在get_current_time函数中我们就可以通过$params['local']来获得属性值。 如果在get_current_time函数中需要用到当前smarty对象的方法或属性,就可以通过第二个参数获得。
这时你会发现index.tpl已被缓存,但当前时间却随每次刷新在不断变化。
2、使用register_function阻止插件从缓存中输出 index.tpl: <div>{current_time}{/div}
index.php: function smarty_function_current_time($params, &$smarty){ return date([Y-m-d H:m:s]); }
$smarty=new smarty(); $smarty->caching = true; $smarty->register_function(‘current_time’,’smarty_function_current_time’,false); if(!$smarty->is_cached()){ ……. } $smarty->display(‘index.tpl’);
注解: 定义一个函数,函数名格式为:smarty_type_name($params, &$smarty) type为function name为用户自定义标签名称,在这里是{current_time} 两个参数是必须的,即使在函数中没有使用也要写上。两个参数的功能同上。