smarty 的过滤器

‍smarty 的过滤器 分为
• Prefilter
• Postfilter
• Output filter
这三种,这里分别解释一下
Prefilter:在smarty模板编译成php代码之前调用
Postfilter:在smarty模板编译成php代码之后调用
Output Filters:在smarty 准备显示编译过的代码时调用
这里的顺序应该是 tpl源文件 =〉Prefilter =〉编译tpl文件 => Postfilter =>保存到磁盘=> 编译过的php文件执行=〉Output Filters(=〉如果有smarty cache的话,Output Filters的内容会缓存) =>结果输出。

创建filter的方式也一般有三种:
1:执行时 注册一个 filter,此时可以用以下三种函数调用:
Prefilters         void register_prefilter(mixed impl)
Postfilters      void register_postfilter(mixed impl)
Output filters void register_outputfilter(mixed impl)
这里的impl 指 回调的函数名, 或者形如:array($object, 'method_name')或array('class_name', 'method_name')的数组

执行时 注册的例子:
function highlight($output, &$smarty)
{
// highlight the word "smarty" on our template source
return str_replace('smarty', '<b>smarty</b>', $output);
}
$smarty->register_outputfilter('highlight');
$smarty->display('templates/example1.tpl');
2:手动加载一个过滤器
一个过滤器插件的文件应该放在plug-in目录里面,而且文件 和 函数的命名也要遵循一定的规则
如:一个prefilter,那么他的文件名应为:prefilter.nameoffilter.php , 其函数名字应为:smarty_prefilter_nameoffilter($source, &$samrty);
如以下函数:
function smarty_outputfilter_append_benchmark_data($source, &$smarty)
{
global $benchmark;
$source .= '<div id="benchmark">';
$source .= 'Generated in ' . $benchmark . ' secs.';
$source .= '</div>';
return $source;
}
?>
保存在outputfilter.append_benchmark_data.php这个文件里面,
我们调用这个插件时:
$smarty->load_filter('output', 'append_benchmark_data');
3:自动加载的过滤器
这里我们需要修改:Smarty.class.php文件里面的autoload_filters 这个变量,格式如下:
var $autoload_filters = array('output' => array('append_benchmark_data'));

以下就以一个过滤 源文件中的注释代码的过滤器来说明一下怎么写 过滤器插件:
include_once('libs/Smarty.class.php');
$smarty = new Smarty;
function remove_html_comments($source, &$smarty)
{
// remove any html comments from the template source, even
// if they span multiple lines
return preg_replace('/<!--.*-->/Ums', '', $source);
}
$smarty->register_prefilter('remove_html_comments');
$smarty->load_filter('output', 'trimwhitespace');//加载这个过滤器是为了去掉空行,这过滤器是smarty自带的
$smarty->display('remove_comments.tpl');

这样我们就可以去掉网页原代码里面的一些 注释 和 空行,这样就可以稍微减少点网络传输量,增强一点用户的体验。

我们还可以编写过滤器 来 压缩网页文件 , 或过滤、高量网页中的默写词汇。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值