Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

A key called keys in a hash in Template Toolkit

by szabgab (Priest)
on Mar 08, 2013 at 15:23 UTC ( [id://1022446]=perlquestion: print w/replies, xml ) Need Help??

szabgab has asked for the wisdom of the Perl Monks concerning the following question:

I use Template Toolkit to display an HTML page. I have code like this:
<% FOR k IN kw.keys.sort %> <li><% k %> <ul> <% FOR page IN kw.$k.keys %> <li><a href="/<% page %>"><% kw.$k.$page %></a></li> <% END %> </ul> </li> <% END %>
that worked well, until today when I added a key to the 'kw' hash called 'keys'.

Now, instead of fetching all the keys of kw, it only fetches the single field which is called 'keys'. So instead of displaying a nice list of items, it only displayes one.

How can I convince TT to use the keys function to retreive all the keys again?

Replies are listed 'Best First'.
Re: A key called keys in a hash in Template Toolkit
by mbethke (Hermit) on Mar 08, 2013 at 16:30 UTC

    TTBOMK you can't, that's the downside of the simplified dot syntax. What you can try however is to iterate the hash without using .keys. Template::Manual::Directives has this example:

    [% FOREACH u IN users %] * [% u.key %] : [% u.value %] [% END %]
    FOREACH automatically sorts by key if you use the iterator that way.

Re: A key called keys in a hash in Template Toolkit
by Anonymous Monk on Mar 08, 2013 at 23:58 UTC

    Well, you could write a Template::Plugin that makes available a keys/sort/sortedkey function, so you could write sortedkeys(kw) and it'd work

    Or you could write a class to call vmethods and use it with Template::Plugin::Class like

    [% USE vm = Class('TemplateX::VMethodCaller'); FOR k IN vm.sort( vm.keys(kw) ); %]

    Look inside Template::VMethods and Template::Stash (esp dotop)

    Or you could realize that keys isn't a particularly swell keyname :) and change it -- unless you're programming a piano/keyboard :p

Re: A key called keys in a hash in Template Toolkit (define_vmethod)
by Anonymous Monk on Mar 09, 2013 at 00:22 UTC

    Add your own vmethod

    $tt->context->define_vmethod( hash => vm_keys => \&Template::VMethods::hash_keys );
    Then kw.vm_keys.sort works, but naturally it breaks if you define a key called "vm_keys"

    You can't have _keys as those are ignored by dodot, they're private

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1022446]
Approved by marto
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-07-22 13:51 GMT
Find Nodes?
    Voting Booth?

    No recent polls found

    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.