Category: Catalyst Keywords: Template Filter
所谓 filter, 过滤器。想像一下咖啡的过滤器,想像下香烟的过滤嘴。Template 的过滤器也差不多。我打算先介绍下 TT 内置的一些 filters, 然后明天介绍下如何写自己的 filter.
builtin filters
恐怕最最常用的一个 filter 就是 html, filter 的用法有以下几种:[% FILTER html %]TT 给懒人们弄了个简单的符号 | 用以代替 FILTER 这六个英文字母。所以你也可以这么写:
<script language="JavaScript" type="text/javascript">
<!--
document.writeln("Hello, world");
//-->
</script>
[% END %]
[% | html %]另一种是外来的一个变量或者在其他地方定义的一个变量。比如我们在其他的模版里定义了:
[% output = '<script language="JavaScript" type="text/javascript">到时候我们输出的话可以这么写:
<!--
document.writeln("Hello, world");
//-->
</script>' %]
[% output | html %]我们还可以使用多个 filters.
# or [% output FILTER html %]
[% output | html | truncate(30) %]以上差不多就是所有 filter 的用法。
- 另外的一些内置 filter 有
- format format 与 html 不同,它是一个动态 filter, 可以接受参数。比如:(用途类似 sprintf)
[% pi = 3.1415926536 %]
这样输出的结果为 3.142
[% pi | format('%0.3f') %] - collapse 这个内置的 filter 将所有的所有多于一个空格的大空白过滤为一个空格。如:
[% FILTER collapse %]
输出的结果为:You'll love it, it's a way of life.
You'll love it, it's a way of life.
[% END %] - eval / evaltt 将变量作为 TT 模版来运行。这个变量一般是从外面传进来的。比如:
my $vars = {
fragment => "The cat sat on the [% place %]",
};
$tt->process($file, $vars);
|| die $tt->error( );[% fragment | eval %]
能将 [% place %] 用变量 place 代替掉。evaltt 跟 eval 是等同的。 - indent(pad) 用于缩进。比如我们回复信件的时候一般在原来的信件内容前加“> ”,在 TT 中就可以这么写:
[% FILTER indent("> ") -%]输出的结果为:
Dear Fayland,Would u help me to ..Best Regards,
[% END %]> Dear Fayland,
>
> Would u help me to ..
>
> Best Regards, - lcfirst/ucfirst/lower/upper 如字面意思所写的,首字小写/大写/全部小写/大写
- remove(string) 用正则表达式移除一些字符。如:
[% string = "Hello, I must be going.";
输出:Hllo, I must b going. 我们还有更复杂的正则表达式:
string | remove("e") %][% string = "Hello, I must be going.";
这个表达式用于匹配以 H 开头后接 e 再接 ll 但不移除 H 和 ll 的表达式。
string | remove("(?x) # whitespace is not important
(?<=H) # an 'H'
e # strip the 'e'!
(?=ll) # followed by 'll'
") %] - replace(search, replace) 以 remove 不同的是代替。remove 查不多是将 replace(string, '')
[% string = "Hello, I must be going.";
输出:Hullo, I must bu going.
string | replace("e", "u") %] - repeat(iterations) 重复几次。
[% FILTER repeat(5) %]
将这句重复输出 5 次。
I love Perl only less than my girl.
[% END %] - trim 将前后空格去掉。
- truncate(length) 截取前 length 个字符。我们常见的一个描述然后 Read More.. 就可以这样子:
[% FOREACH result = results %]
* [% result.description | truncate(24) %]
<a href="[% result.link %]">Read more</a>
[% END %] - uri 将 uri 变为浏览器所喜欢的形式。类似 URI::Escape 的功能。
- 还有其他一些,查看 TT 的 documents