Java Freemarker 迭代哈希映射键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1497777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:29:23  来源:igfitidea点击:

Freemarker iterating over hashmap keys

javafreemarker

提问by tzador

Freemarker has two collection datatypes, lists and hashmaps Is there a way to iterate over hashmap keys just as we do with lists?

Freemarker 有两种集合数据类型,列表和哈希映射 有没有办法像我们对列表一样迭代哈希映射键?

So if I have a var with data lets say:

所以如果我有一个带有数据的 var 可以说:

user : {
  name : "user"
  email : "[email protected]"
  homepage : "http://nosuchpage.org"
}

I would like to print all the user's properties with their value. This is invalid, but the goal is clear:

我想用它们的值打印所有用户的属性。这是无效的,但目标很明确:

<#list user.props() as prop>
  ${prop} = ${user.get(prop)}
</#list>

采纳答案by skaffman

Edit:Don't use this solution with FreeMarker 2.3.25 and up, especially not .get(prop). See other answers.

编辑:不要在 FreeMarker 2.3.25 及更高版本中使用此解决方案,尤其是.get(prop). 查看其他答案。

You use the built-in keysfunction, e.g. this should work:

您使用内置的功能,例如这应该可以工作:

<#list user?keys as prop>
    ${prop} = ${user.get(prop)}
</#list>  

回答by Nick Spacek

FYI, it looks like the syntax for retrieving the values has changed according to:

仅供参考,检索值的语法似乎已根据以下内容发生变化:

http://freemarker.sourceforge.net/docs/ref_builtins_hash.html

http://freemarker.sourceforge.net/docs/ref_builtins_hash.html

<#assign h = {"name":"mouse", "price":50}>
<#assign keys = h?keys>
<#list keys as key>${key} = ${h[key]}; </#list>

回答by rees

If using a BeansWrapperwith an exposure level of Expose.SAFE or Expose.ALL, then the standard Java approach of iterating the entry set can be employed:

如果使用BeansWrapper与Expose.SAFE或Expose.ALL,的曝光电平,那么条目组可以采用迭代的标准的Java的方法:

For example, the following will work in Freemarker (since at least version 2.3.19):

例如,以下内容将适用于 Freemarker(至少从 2.3.19 版开始):

<#list map.entrySet() as entry>  
  <input type="hidden" name="${entry.key}" value="${entry.value}" />
</#list>

In Struts2, for instance, an extension of the BeanWrapperis used with the exposure level defaulted to allow this manner of iteration.

例如,在 Struts2 中,使用了 BeanWrapper 的扩展,默认暴露级别允许这种迭代方式。

回答by Ashish Chhabria

You can use a single quote to access the key that you set in your Java program.

If you set a Map in Java like this

您可以使用单引号来访问您在 Java 程序中设置的密钥。

如果您像这样在 Java 中设置 Map

Map<String,Object> hash = new HashMap<String,Object>();
hash.put("firstname", "a");
hash.put("lastname", "b");

Map<String,Object> map = new HashMap<String,Object>();
map.put("hash", hash);

Then you can access the members of 'hash' in Freemarker like this -

然后你可以像这样在 Freemarker 中访问“hash”的成员 -

${hash['firstname']}
${hash['lastname']}

Output :

输出 :

a
b

回答by Tk421

Iterating Objects

迭代对象

If your map keys is an object and not an string, you can iterate it using Freemarker.

如果您的地图键是一个对象而不是一个字符串,您可以使用 Freemarker 对其进行迭代。

1) Convert the map into a list in the controller:

1)在控制器中将地图转换为列表:

List<Map.Entry<myObjectKey, myObjectValue>> convertedMap  = new ArrayList(originalMap.entrySet());

2) Iterate the map in the Freemarker template, accessing to the object in the Key and the Object in the Value:

2)迭代Freemarker模板中的map,访问Key中的对象和Value中的Object:

<#list convertedMap as item>
    <#assign myObjectKey = item.getKey()/>
    <#assign myObjectValue = item.getValue()/>
    [...]
</#list>

回答by ddekany

Since 2.3.25, do it like this:

从 2.3.25 开始,这样做:

<#list user as propName, propValue>
  ${propName} = ${propValue}
</#list>

Note that this also works with non-string keys (unlike map[key], which had to be written as map?api.get(key)then).

请注意,这也适用于非字符串键(不像map[key],必须像map?api.get(key)then那样编写)。

Before 2.3.25 the standard solution was:

在 2.3.25 之前的标准解决方案是:

<#list user?keys as prop>
  ${prop} = ${user[prop]}
</#list>

However, some really old FreeMarker integrations use a strange configuration, where the public Mapmethods (like getClass) appear as keys. That happens as they are using a pure BeansWrapper(instead of DefaultObjectWrapper) whose simpleMapWrapperproperty was left on false. You should avoid such a setup, as it mixes the methods with real Mapentries. But if you run into such unfortunate setup, the way to escape the situation is using the exposed Java methods, such as user.entrySet(), user.get(key), etc., and not using the template language constructs like ?keysor user[key].

然而,一些非常古老的 FreeMarker 集成使用了一种奇怪的配置,其中公共Map方法(如getClass)显示为键。发生这种情况是因为他们使用的是纯的BeansWrapper(而不是DefaultObjectWrapper),其simpleMapWrapper属性保留在false. 您应该避免这种设置,因为它将方法与真实Map条目混合在一起。但是,如果你碰上这样倒霉的设置,为了躲避情况的方法是使用公开的Java方法,如user.entrySet()user.get(key)等,并没有使用模板语言结构,如?keysuser[key]

回答by Ondra ?i?ka

For completeness, it's worth mentioning there's a decent handling of empty collections in Freemarker since recently.

为完整起见,值得一提的是,自最近以来,Freemarker 中对空集合的处理方式不错。

So the most convenient way to iterate a map is:

所以迭代地图最方便的方法是:

<#list tags>
<ul class="posts">
    <#items as tagName, tagCount>
        <li>{$tagName} (${tagCount})</li>
    </#items>
</ul>
<#else>
    <p>No tags found.</p>
</#list>

No more <#if ...>wrappers.

没有更多的<#if ...>包装。