【问题标题】:Freemarker and hashmap. How do I get key-valueFreemarker 和 hashmap。我如何获得键值
【发布时间】:2013-01-27 02:19:46
【问题描述】:

我有一个如下的哈希映射

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 中显示键值对。请帮我做。谢谢!

【问题讨论】:

  • 显示了什么?错误在哪里?

标签: java html freemarker


【解决方案1】:

代码:

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>

【讨论】:

【解决方案2】:

使用保留键值对插入顺序的映射:LinkedHashMap

【讨论】:

  • 这个答案是假设问题是输出不是插入顺序。我不确定这是不是真的。
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

    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>
    

    【讨论】:

    • 这是有史以来最丑陋的解决方案,但是,当我将 LONG 作为哈希中的键并且我需要稍后保留和使用该键时,它可以正常工作
    • 如果键和值是更复杂的 java bean,而不仅仅是字符串,也可以正常工作:)
    猜你喜欢
    • 2010-12-02
    • 2019-01-10
    • 2013-04-21
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 2018-10-29
    相关资源
    最近更新 更多