Add attributes to element in template toolkit

289 Views Asked by At

Perl code

Passing menu items as perl array containing link hashes

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 },
    }                                                       
];

Template Toolkit Code

Accessing the links using template toolkit for each

<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>

What I have tried

I tried assigning all params to a variable with key and value both and then assigning it to the corresponding link

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

Problem

The params are not coming in the link only href is printed and link text is printed

Expected Result

<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>
1

There are 1 best solutions below

1
On

I will tried again, you can achieve your goal like this.

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

Because in the template, if you directly use the hash, it will recognized it as a hash ref in the template. It can not be parsed directly in your file with the pattern like key=value