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 に答える
4

キーと値のペアの挿入順序を保持するマップを使用します: LinkedHashMap

于 2014-03-06T13:24:13.433 に答える