user1629109 user1629109 - 1 year ago 194
Java Question

Freemarker and hashmap. How do I get key-value

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:

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

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

Answer Source


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


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


    two = 2 
    one = 1 
    three = 3 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download