四、DWOO的过滤器
同样,dwoo中也支持用户编写过滤器,它可以在模版内容向用户输出前进行一些相关的操作,跟插件类似,可以使用addFilter()加载自己编写的过滤器,例子如下:
<?php
function activate_mailto_links(Dwoo $dwoo, $str) {
return preg_replace('/([a-zA-Z0-9]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+)/', '<a href="mailto:$1">$1</a>', $str);
}
include 'dwooAutoload.php';
try {
$dwoo = new Dwoo();
$dwoo->addFilter('activate_mailto_links');
$tpl = new Dwoo_Template_File('tmpl/filter.tpl');
$data['string']= 'Press enquiries: press@example-domain.com or call 1-800-1234. General inquiries: info@example-domain.com.';
$dwoo->output($tpl, $data);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
function activate_mailto_links(Dwoo $dwoo, $str) {
return preg_replace('/([a-zA-Z0-9]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+)/', '<a href="mailto:$1">$1</a>', $str);
}
include 'dwooAutoload.php';
try {
$dwoo = new Dwoo();
$dwoo->addFilter('activate_mailto_links');
$tpl = new Dwoo_Template_File('tmpl/filter.tpl');
$data['string']= 'Press enquiries: press@example-domain.com or call 1-800-1234. General inquiries: info@example-domain.com.';
$dwoo->output($tpl, $data);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
这个例子的过滤器中,作用是自动把模版合成输出后的内容中的含有的邮件地址自动加上mailto:的邮件链接。结果如下输出:
同样,也可以这样写:
<?php
class Dwoo_Filter_activate_mailto_links extends Dwoo_Filter
{
public function process($str)
{
return preg_replace('/([a-zA-Z0-9]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+)/', '<a href="mailto:$1">$1</a>', $str);
}
}
?>
class Dwoo_Filter_activate_mailto_links extends Dwoo_Filter
{
public function process($str)
{
return preg_replace('/([a-zA-Z0-9]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+)/', '<a href="mailto:$1">$1</a>', $str);
}
}
?>
把该文件保存在dwoo下的plugins目录中,同样DWOO会自动加载。