自由标记和哈希图。我如何获得键值

新手上路,请多包涵

我有一个哈希映射如下

HashMap<String, String> map = new HashMap<String, String>();
map.put("one", "1");
map.put("two", "2");
map.put("three", "3");

Map root = new HashMap();
root.put("hello", map);

我的 Freemarker 模板是:

 <html><body>
    <#list hello?keys as key>
        ${key} = ${hello[key]}
    </#list>
</body></html>

目标是在我生成的 HTML 中显示键值对。请帮我做。谢谢!

原文由 Damien-Amen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 294
2 个回答

代码:

 Map root = new HashMap();
HashMap<String, String> test1 = new HashMap<String, String>();
test1.put("one", "1");
test1.put("two", "2");
test1.put("three", "3");
root.put("hello", test1);

Configuration cfg = new Configuration(); // Create configuration
Template template = cfg.getTemplate("test.ftl"); // Filename of your template

StringWriter sw = new StringWriter(); // So you can use the output as String
template.process(root, sw); // process the template to output

System.out.println(sw); // eg. output your result

模板:

 <body>
<#list hello?keys as key>
    ${key} = ${hello[key]}
</#list>
</body>

输出:

 <body>
    two = 2
    one = 1
    three = 3
</body>

原文由 ollo 发布,翻译遵循 CC BY-SA 4.0 许可协议

从 2.3.25 开始,您可以这样做:

 <body>
<#list hello as key, value>
    ${key} = ${value}
</#list>
</body>

原文由 ddekany 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题