最好在控制器中进行这种数据处理。模板工具包的工作实际上是布置东西并使它们漂亮,而不是做“计算”。
你想要的更像是:
[% SET list = formatter.group_them('namelist.txt') %]
[% FOREACH item IN list %]
[% item.key %]
[% FOREACH name IN item.value %]
[% name %]
[% END %]
[% END %]
可以通过多种方式做你想做的事。可以使用 VMethods http://template-toolkit.org/docs/manual/VMethods.html进行拆分,创建数组,再次拆分,构建哈希:
[% data = INSERT 'namelist.txt' %]
[% lines = data.split("\n") %]\
[% list = {} %]
[% FOREACH line IN lines %]
[% pair = line.split(': ') %]
[% city = pair.0; name = pair.1; list.city.push(name) %]
[% END %]
好吧,我不得不承认,在我继承的模板中看到这一点我会感到羞愧。但有时我们会出于充分的理由做一些让他人感到羞愧的事情......当时...... :-)
稍微好一点的方法是插入
[% RAWPERL %]
block. At least then, you are admitting, you have code within the template and doing the operations in a natural and efficient way.