简体   繁体   English

从模板工具包中的键中查找哈希值

[英]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. KEY即将来临.....我尝试过很多东西,但是没有用。

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. 您可以使用pairs vmethod获取键/值对的列表,然后可以按顺序对其进行排序。

[% 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. 不幸的是,查看TT中可用的哈希虚拟方法 ,我认为没有办法在您的模板中完全执行此操作。 You'll need to massage the data a little in code first, either through the sort above, or by inverting the hash: 您需要先通过上面的sort或通过反转哈希来对代码中的数据进行一点按摩:

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. 如果反转散列,则可以使用TT 方法一次性获取键/值对的排序列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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