Freemarker and hashmap. How do I get key-value

孤街浪徒 提交于 2019-12-17 23:52:42

问题


I have a hash map as below

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);

My Freemarker template is:

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

The goal is to display key-value pair in the HTML that I'm generating. Please help me to do it. Thanks!


回答1:


Code:

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

Template:

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

Output:

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



回答2:


Since 2.3.25, you can do this:

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



回答3:


Use a map that preserves the insertion order of the key-value pairs: LinkedHashMap




回答4:


Before 2.3.25, in case of keys containing objects, you can try to use

<#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>


来源:https://stackoverflow.com/questions/14821329/freemarker-and-hashmap-how-do-i-get-key-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!