【问题标题】:Using a variable to access hash keys in Template Toolkit在 Template Toolkit 中使用变量访问哈希键
【发布时间】:2014-04-16 10:34:11
【问题描述】:

我有一个数组,其内容是

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

我正在尝试在催化剂模板中显示,代码是

[% 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 %]

根据 x 的值,dateformat.x 应该显示 May 05, 2011 或 Jul 22, 2009 或 Jun 13, 2012,但错误是它什么都不显示。它显示一个空白。

我认为的错误是数组中的键是字符串,而与 dateformat 一起使用的 x 的值是数字。如果我在 dateformat 中添加 0 或 1,那么它会正确显示([% dateformat.0 %])。

【问题讨论】:

  • 我不明白您要做什么以及出了什么问题。或者甚至是否有问题,看看你如何只声明某些东西显示正确。可能只是我,但如果你想回答一些问题,我个人建议你改写你的问题。

标签: perl template-toolkit


【解决方案1】:

[% dateformat.x %]dateformat 哈希中查找x 的键。要告诉模板工具包x 是一个变量,请在其前面加上$

[% dateformat.$x %]

要使用存储在另一个变量中的键访问哈希条目,请在键变量前面加上“$”,以便在使用前对其进行插值(请参阅Variable Interpolation)。

【讨论】:

    【解决方案2】:

    我很欣赏这个问题已经被问到并得到了回答,但一个方便的替代方案是item()VMethod。这在您的哈希键与 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"
    -%]
    

    firstlastsizesort 等 VMethod 是粗心的人的常见陷阱。

    【讨论】:

    • 我特别赞成你如何在 Template Toolkit 中声明散列变量的方法,因为我一直在寻找它并最终来到了这里。
    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多