how to reverse an anonymous list in template toolkit?
Is it possible to reverse an anonymous list in template toolkit开发者_Go百科?
e.g.
[% FOREACH month IN [1..12].reverse %]
[% month %]
[% END %]
(except that doesn't work).
Just wondered if there was a neat way to do it without using variables or explicitly typing out the array.
Sorry, there isn't. Being able to instantiate anonymous arrays in situ is a special case handled by the TT parser. You can't operate on them like you can in regular Perl without the intermediate step of assigning to a named variable.
EDIT: You can't even pass in a subroutine to try to use like so:
[% FOREACH month IN my_reverse([1..12]) %]
[% month %]
[% END %]
Nor can you try to use a method on an object:
[% FOREACH month IN testObj.my_reverse([1..12]) %]
[% month %]
[% END %]
They will compile, but in each case, the FOREACH
construct sees the head of the chain, e.g. a CODE
reference in the first case and a blessed object in the second.
I'm a little new but what about this:
[% months = ['jan','feb','mar',...]; ## array of months
[% FOREACH i = [(months.size-1)-1 .. 0] %] ## counts -11 to 0 for 12 elements [% months[(i-1)] ## converts i to positive number - displays months[11], months[10] ... months[0]
<!-- show 2010 2009 2008 2007 -->
[% SET startyear = 2007 %]
[% SET endyear = 2010 %]
[% SET allyears = [ startyear .. endyear ] %]
[% FOREACH year IN alleyears.reverse %]
<li>[% year %]</li>
[% END %]
精彩评论