6
[% a = ['one', 'two', 'four'] %]
[% a.1 %] # it prints two. OK!

But when I want this:

[% a = ['one', 'two', 'four'] %]
[% n = 1 %]
[% a.n %] # it doesn't work

How can I use var n in order to get defined element from array?

edem
  • 3,222
  • 3
  • 19
  • 45

1 Answers1

14

Template Toolkit has same access to list and hash elements - through dot operator. In your code TT thinks that you want to get value in hash a by key 'n'. Solution is to use prefix $ before your actual variable in dot operator, in you case:

[% a = ['one', 'two', 'four'] %]
[% n = 1 %]
[% a.$n %] # now it works
alexlopashev
  • 186
  • 1
  • 4
  • 3
    Another way to do this is to use `[% a.item(n) %]`, which is necessary when you have keys in your hash that are also VMethod names. `.keys`, `.sort`, `.index` are classic examples that can trip you up here. – RET Mar 27 '13 at 02:49