java 如何在java中使用mustache迭代地图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26452209/
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
How to iterate over map using mustache in java
提问by Simple-Solution
I'm newbie to mustache and was wondering how to iterate over HashMap
using mustache given this Map
我是 mustache 的新手,想知道如何迭代HashMap
使用 mustache 给定这个Map
Map mapA = new HashMap();
mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");
The map key names vary. Ideally, I want mustache to iterate over both its key and values. So in java it will look like this:
地图键名各不相同。理想情况下,我希望 mustache 迭代其键和值。所以在java中它看起来像这样:
for (Map.Entry<String, Object> entry : mapA.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}
So can someone tell me how to achieve above in mustache. I mean how would the template looks like? I tried this template but had no luck so far :(
那么有人可以告诉我如何在胡子上实现上述目标。我的意思是模板会是什么样子?我试过这个模板,但到目前为止没有运气:(
{{#mapA}}
<li>{{key}}</li>
<li>{{value}}</li>
{{/mapA>
So when I run this template, the output <li>
tags comes out empty, why?
Thanks.
所以当我运行这个模板时,输出<li>
标签是空的,为什么?谢谢。
采纳答案by Dici
I don't know mustachebut basing on some samples of code I have seen, I think you should define an entrySet
variable in your Java code like this
我不知道mustache但根据我看到的一些代码示例,我认为您应该entrySet
在 Java 代码中定义一个这样的变量
Set<Map.Entry<String,Object>> entrySet = mapA.entrySet();
and use it instead of mapA
in your mustachecode
并mapA
在您的胡子代码中使用它而不是
{{#entrySet}}
<li>{{key}}</li>
<li>{{value}}</li>
{{/entrySet}}
回答by milesoldenburg
As @Dici mentioned above, you can use an entrySet
. You do not have to use any special options on the factory and can pass it directly to execute
. In your template you can use a top level map if your template is very simple.
正如@Dici 上面提到的,您可以使用entrySet
. 您不必在工厂中使用任何特殊选项,可以直接将其传递给execute
. 如果您的模板非常简单,您可以在您的模板中使用顶级地图。
Java
爪哇
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
Writer writer = new OutputStreamWriter(System.out);
MustacheFactory mustacheFactory = new DefaultMustacheFactory();
Mustache template = mustacheFactory.compile("map.template");
template.execute(writer, map.entrySet()).close();
Mustache Template (map.template
)
小胡子模板 ( map.template
)
{{#.}}
keylabel:{{key}} : valuelabel:{{value}}
{{/.}}
Result
结果
keylabel:key1 : valuelabel:value1
keylabel:key2 : valuelabel:value2