Freemarker和hashmap.我如何获得键值

Dam*_*men 20 html java freemarker

我有一个哈希映射如下

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);
Run Code Online (Sandbox Code Playgroud)

我的Freemarker模板是:

<html><body>
    <#list hello?keys as key> 
        ${key} = ${hello[key]} 
    </#list> 
</body></html>
Run Code Online (Sandbox Code Playgroud)

目标是在我生成的HTML中显示键值对.请帮我做.谢谢!

oll*_*llo 43

码:

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
Run Code Online (Sandbox Code Playgroud)

模板:

<body>
<#list hello?keys as key> 
    ${key} = ${hello[key]} 
</#list> 
</body>
Run Code Online (Sandbox Code Playgroud)

输出:

<body>
    two = 2 
    one = 1 
    three = 3 
</body>
Run Code Online (Sandbox Code Playgroud)

  • 从2.3.25开始,有更好的方法; 请参阅:/sf/answers/2679143491/ (7认同)

dde*_*any 21

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

<body>
<#list hello as key, value> 
    ${key} = ${value} 
</#list> 
</body>
Run Code Online (Sandbox Code Playgroud)


gia*_*olm 5

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>
Run Code Online (Sandbox Code Playgroud)

  • 这是有史以来最丑陋的解决方案,但是,当我在哈希中有一个 LONG 作为密钥并且我需要稍后保留和使用该密钥时,它工作得很好 (3认同)