访问键在变量中的 FreeMarker 映射

Access FreeMarker map where the key is in a variable

我有一个 Apache FreeMarker "map" 变量,我需要访问地图中的一个元素。问题是我要查找的元素的 "key" 存储在变量本身中。考虑以下地图:

<#assign mymap = {"key1" : "value1", "key2" : "value2"}>

现在我可以通过这样的方式轻松访问地图:

${mymap.key1}

这很好用。我的问题是 "key1" 包含在这样的变量中:

<#assign keyname = "key1">
<-- Now I want to access the map via whatever key is in the variable keyname -->
${mymap.${keyname}}

很遗憾,上述语法是非法的。我猜想 FreeMarker 不够智能,无法执行嵌套插值。那么,我该如何实现呢?对文档的粗略检查似乎并没有真正谈论这种情况。不过,这似乎很常见。

对散列使用alternative syntax

 mymap[keyname]

There is an alternative syntax if we want to specify the subvariable name with an expression: book["title"]. In the square brackets you can give any expression as long as it evaluates to a string. So with this data-model you can also read the title with book[test]. More examples; these are all equivalent: book.author.name, book["author"].name, book.author["name"], book["author"]["name"].