Freemarker和HashMap。如何获取键值对?

27

我有一个以下的哈希表

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中显示键值对。请帮助我完成它。谢谢!


2
显示了什么?错误在哪里? - Aubin
4个回答

51

代码:

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>

7
从2.3.25开始,有一种更好的方法;请参见:https://dev59.com/kGUq5IYBdhLWcg3wEcRZ#38273478 - ddekany

25

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

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

5

在2.3.25版本之前,如果键包含对象,您可以尝试使用

<#assign key_list = map?keys/>
<#assign value_list = map?values/>
<#list key_list as key>
  ...
  <#assign seq_index = key_list?seq_index_of(key) />
  <#assign key_value = value_list[seq_index]/>
  ...
     //Use the ${key_value}
  ...
</#list>

3
这可能是最丑陋的解决方案,但是当我在哈希表中使用LONG作为键并且需要保留和以后使用该键时,它仍然能够正常工作。 - ryzhman
如果键和值是更复杂的Java Bean,而不仅仅是字符串,也可以正常工作 :) - Andreas Hauschild

4
使用一个保留键值对插入顺序的映射:LinkedHashMap。

2
假设问题是输出不按插入顺序排列,本回答将基于此前提。但我不确定这是否属实。 - Gray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接