开发者

Creating a grouped output using Template toolkit

I have a datafile

city : name
London : John
London : George
Paris : Jean

And I would like output

London 
    John
    George
Paris 
    Jean

I feel i want something like

[% USE namelist = datafile( 'namelist.txt' )  %]
[%   FOREACH city = unique namelist.city ???  %]
[% city %]
[%   FOREACH name =????  %]
[% name %]
开发者_StackOverflow中文版
[%END %]    
[%END %]


It is probably best to do this kind of data munging in your controller. Template toolkit's job is really to lay things out and make them pretty, not do "calculations".

What you want is something more like:

 [% SET list = formatter.group_them('namelist.txt') %]
 [% FOREACH item IN list %]
 [% item.key %]
    [% FOREACH name IN item.value %]
        [% name %]
    [% END %]
 [% END %]

It is possible to do what you want in a variety of ways. You can use VMethods http://template-toolkit.org/docs/manual/VMethods.html to split, create an array, split again, build a hash:

[% 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 %]

OK, I have to admit, I would be mortified to see this in a template I inherited. But sometimes we do things that mortify others for a good reason... at the time... :-)

A slightly better approach is to insert

[% RAWPERL %] 

block. At least then, you are admitting, you have code within the template and doing the operations in a natural and efficient way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜