[Templates] loop first, loop last in current version
Sean McAfee
eefacm at gmail.com
Mon Sep 22 05:20:33 BST 2008
On Mon, Sep 15, 2008 at 6:29 AM, Birgit Kellner <birgit.kellner at univie.ac.at
> wrote:
> Hi,
>
> in an older version of the Template Toolkit (we just updated our server
> to 2.19), using <% if loop.last %> threw an error that could be solved
> through a hack in Iterator.pm, sub AUTOLOAD:
>
> $item = 'LAST' if $item eq 'loop_final';
>
> This hack no longer works, and <%if loop.last %> still throws an error:
>
> file error - parse error - pub_author.tmpl line 3: unexpected token
> (LAST) [% if not loop.last %].
>
> Any ideas how to remedy this?
>
I was able to get the behavior you wanted without any source hacking, by
writing my own subclass of Template::Parser. It turns any LAST token that
follows a DOT token into an IDENT token:
use Template;
use Template::Parser;
use strict;
package MyParser;
our @ISA = qw(Template::Parser);
sub tokenise_directive {
my $self = shift;
my $tokens = $self->SUPER::tokenise_directive(@_);
for (my $i = 0; $i < @$tokens; $i += 2) {
if ($tokens->[$i] eq 'LAST' && $i > 0 && $tokens->[$i-2] eq 'DOT') {
splice @$tokens, $i, 2, 'IDENT', 'last';
}
}
return $tokens;
}
package main;
my $t = Template->new({ PARSER => MyParser->new({ ANYCASE => 1 }) };
$t->process(\*DATA) or die $t->error;
__DATA__
[% for x in [ 1, 2, 3 ]; x; "," if not loop.last; end %]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.template-toolkit.org/pipermail/templates/attachments/20080921/51f48a65/attachment.htm
More information about the templates
mailing list