Search code examples
template-toolkit

Iterate over hashref Template Toolkit


The data that I'm passing to the template is as follows:

This is the 'tickets' hashref used in the following foreach:

$VAR1 = {
    '1234' => {'request_time' => '1405392890', 'id' => '1234'},
    '9993' => {'request_time' => '1485035309', 'id' => '9993'}
};

I am doing the following:

[% FOREACH ticket IN tickets %]
    <td>[% ticket.request_time %]</td>
    <td>[% ticket.id %]</td>
[% END -%]

But this doesn't seem to display anything. Could someone point out where I'm wrong?


Solution

  • You also need to be careful that TT doesn't treat a numeric hash-key as an array-element reference. If there's a risk of confusion (or if you have a clash between hash-keys and vmethod names), then the vmethod item() is particularly useful:

    [% FOREACH ticket IN tickets.keys.nsort %]
        <td>[% tickets.item(ticket).request_time %]</td>
        <td>[% ticket %]</td>
    [% END -%]