简体   繁体   中英

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?

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM