سؤال

I have an array whose contents is

$VAR1 = {
'1' => 'May 05, 2011',
'0' => 'Jul 22, 2009',
'2' => 'Jun 13, 2012'
};

I am trying to display it in the catalyst template, the code is

[% x = 0 %]
[% FOREACH mortgage IN mortgages %]

<table width=40% border=1 cellspacing="0" cellpadding="10">
    <tr>
        <td>Date</td>
        <td><b>[% dateformat.x %]</b></td>
    </tr>
 </table>
[% x = x+1 %]
[% END %]

The dateformat.x should display May 05, 2011 or Jul 22, 2009 or Jun 13, 2012 according to the value of x but the error is that it displays nothing. It shows a blank .

The error I think is that the key in the array is a string while the value of x that is used with the dateformat is numeric. If I add 0 or 1 with the dateformat then it displays correctly([% dateformat.0 %]).

هل كانت مفيدة؟

المحلول

[% dateformat.x %] looks in the dateformat hash for a key of x. To tell template toolkit that x is a variable, prefix it with $:

[% dateformat.$x %]

To access a hash entry using a key stored in another variable, prefix the key variable with '$' to have it interpolated before use (see Variable Interpolation).

نصائح أخرى

I appreciate this question has already been asked and answered, but a handy alternative is the item() VMethod. This is particularly effective when you have hash keys that conflict with VMethods:

[%- SET myhash = { last => 'Blues', first => 'Elwood',
                   address => '1060 West Addison', city => 'Chicago' };
    myhash.first; # doesn't do what you want,
                  # because first is a VMethod for 1st element in an array
    myhash.item('first'); # displays "Elwood"
-%]

VMethods like first, last, size and sort are common traps for the unwary here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top