2013-02-11 78 views
13

我有一个哈希表如下Freemarker和hashmap。如何获得键值

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显示键值对生成。请帮助我做到这一点。谢谢!

+1

显示什么?错误在哪里? – Aubin 2013-02-11 21:40:52

回答

33

代码:

HashMap<String, String> test1 = new HashMap<String, String>(); 
Map root = new HashMap(); 
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> 
+3

从2.3.25开始有更好的方法;请参阅:https://stackoverflow.com/a/38273478/606679 – ddekany 2017-08-16 17:30:03

3

使用地图,可以保留该键值对的插入顺序:LinkedHashMap的

+0

此答案假设问题是输出不是按插入顺序。我不确定这是否属实。 – Gray 2014-03-09 23:00:29

11

自2.3.25,你可以这样做:

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

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>