使用模板工具包创建分组输出

发布于 2024-10-05 19:08:02 字数 399 浏览 3 评论 0原文

我有一个数据文件

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

,我想要输出

London 
    John
    George
Paris 
    Jean

,我觉得我想要类似的东西

[% USE namelist = datafile( 'namelist.txt' )  %]
[%   FOREACH city = unique namelist.city ???  %]
[% city %]
[%   FOREACH name =????  %]
[% name %]

[%END %]    
[%END %]

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

[%END %]    
[%END %]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

手长情犹 2024-10-12 19:08:02

最好在控制器中进行这种数据处理。模板工具包的工作实际上是布局并使其美观,而不是进行“计算”。

你想要的更像是:

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

块。至少,您承认,您在模板中拥有代码并以自然而有效的方式执行操作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文