Rajeev
Rajeev

Reputation: 1371

find hash value from key in template toolkit

have simple hash, which is being used to pupulate a select option. I want to order it on values, but I am not able to print the keys...

[%- FOREACH val IN myList.values.sort -%]<option value="[%- myList.$val.key -%]">[%- val -%]</option>[% END %]

the KEY is coming null..... i tried many things, it is not working.

so that select option is coming as:

<option value="">roger1</option>

all keys and values are unique.

how can i get the key if i know the value, from a hash?

Upvotes: 1

Views: 1178

Answers (2)

Dave Cross
Dave Cross

Reputation: 69264

You can use the pairs vmethod to get a list of key/value pairs, which you can then sort into the order you want.

[% myList = { first => 'ZZZ', second => 'YYY', third => 'XXX' };
   FOREACH option IN myList.pairs.sort('value') -%]
<option value="[% option.key %]">[% option.value %]</option>
[% END -%]

Output:

<option value="third">XXX</option>
<option value="second">YYY</option>
<option value="first">ZZZ</option>

Upvotes: 3

Matt Jacob
Matt Jacob

Reputation: 6553

This would be easy enough to do by implementing a custom sort by value:

my @keys = sort { $hash{$a} cmp $hash{$b} } keys(%hash);

Unfortunately, looking over the hash virtual methods available in TT, I don't think there's a way to do this purely in your template. You'll need to massage the data a little in code first, either through the sort above, or by inverting the hash:

my %inverted = reverse(%hash);

If you invert the hash, you can use the TT pairs method to get a sorted list of key/value pairs in one shot.

Upvotes: 0

Related Questions