25

我有一个如下的哈希图

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

4

4 回答 4

48

代码:

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>
于 2013-02-11T21:49:33.110 回答
25

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

<body>
<#list hello as key, value> 
    ${key} = ${value} 
</#list> 
</body>
于 2016-07-08T18:46:03.553 回答
4

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

于 2014-03-06T13:24:13.433 回答
4

2.3.25之前,如果key包含对象,可以尝试使用

<#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>
于 2018-02-26T15:58:50.137 回答