【问题标题】:Add attributes to element in template toolkit向模板工具包中的元素添加属性
【发布时间】:2014-01-24 16:49:09
【问题描述】:

Perl 代码

将菜单项作为包含链接哈希的 perl 数组传递

my $bet_details_menu_items = [ 
    {   
        link        => 'link 1',
        text         => 'First',
        is_internal  => 1
    },  
    {   
        link        => 'link 2'
        text        => 'Second',
        params      => { param_name1 => param_value1, param_name2 => param_value2 },
    }                                                       
];

模板工具包代码

使用每个模板工具包访问链接

<ul>
    [% FOREACH item IN menu_items %]
    <li>
        [% IF item.is_internal%]
        <a href="#[% item.link %]">[% item.text %]</a>
        [% ELSE %]
        <a href="[% item.link %]">[% item.text %]</a>
        [% END %]
    </li>
    [% END %]
</ul>

我的尝试

我尝试将所有参数分配给具有键和值的变量,然后将其分配给相应的链接

[% all_params = '' %]
[% FOREACH param IN params.keys %]
[% $all_params = $all_params _  param  _ '=' _ params.$param %]
[% END %] 
[% IF item.is_internal %]
<a href="#[% item.link %]" [% $all_params %] >[% item.text %]</a>
[% ELSE %]
<a href="[% item.link %]" [% $all_params %]>[% item.text %]</a>
[% END %]

问题

参数没有出现在链接中,仅打印 href 并打印链接文本

预期结果

<a href='link 1' // working fine
    param_name1=param_value1 param_name2 param_name2=param_value2 // not working as of now
> link_text //working_fine </a>

【问题讨论】:

  • 页面中的其他元素呢,它们可以正确显示吗?我已经测试过在哈希中传递单个 url 对我来说没有问题。
  • 除参数外一切正常,检查预期结果,刚刚更新了问题
  • 我已经更新了,请查收。

标签: perl template-toolkit


【解决方案1】:

我会再试一次,你可以这样实现你的目标。

<a [% FOREACH item IN $all_params %] [% item.key %] = [% item.value %][% END %] href="#"></a>

因为在模板中,如果直接使用hash,会在模板中识别为hash ref。它不能直接在你的文件中用key=value这样的模式解析

【讨论】:

  • 感谢您的回答,如果我必须将其添加到单个位置,则此方法有效。我想要的是将所有参数分配给单个变量并在我的链接中使用该变量
猜你喜欢
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多