[Templates] Auto-increment?

Josh Rosenbaum josh@infogears.com
Tue, 12 Sep 2006 10:07:15 -0600


Roderick A. Anderson wrote:
> Is there a method to increment a value and have it return that value? 
> I've been through the Badger Book but didn't quite see what I was 
> needing though MACRO seemed close.  This is for a View for a Catalyst 
> based application if that makes a difference.
> 
> I'm looking to accomplish something line this.
> 
> [% tabidx = 81 %]
> 
> <input name="DoIt"    tabindex="[% tabidx++ %]"
>        type="submit" />
> <input name="TryIt"   tabindex="[% tabidx++ %]"
>        type="submit" />
> <input name="IGiveUp" tabindex="[% tabidx++ %]"
>        type="reset" />
> 
> It didn't work when I tried it.  I have ended up doing this. ( It just 
> seems WRONG :-)
> 
> [% tabidx = 81 %]
> 
> <input name="DoIt"    tabindex="[% tabidx %]"
>        type="submit" />
> [% tabidx = tabidx + 1 %]
> <input name="TryIt"   tabindex="[% tabidx %]"
>        type="submit" />
> [% tabidx = tabidx + 1 %]
> <input name="IGiveUp" tabindex="[% tabidx %]"
>        type="reset" />


Rod,

I do not believe there is a way to do this, although you could do:
[% tabidx; tabidx = tabidx + 1 %]

Another idea might be to make tabidx a list ref, and then add a list virtual method.

[% tabidx = [81] %]
[% tabidx.inc() %] <-- will return 81 for display, and increment the value to 82

$Template::Stash::LIST_OPS->{ inc } = sub {
  my $list = shift;
  return $list->[0]++;
};

Might want to call that .pinc for "post increment" since you want it done after the fact. A .inc() should really return an already incremented value probably.

I would've suggested using a scalar here instead, but I don't think scalars are passed by ref, so I don't think your value would ever be updated.

-- Josh