java - Freemarker 和 hashmap。我如何获得键值

标签 java html freemarker

我有一个如下的 HashMap

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

最佳答案

代码:

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>

关于java - Freemarker 和 hashmap。我如何获得键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14821329/

相关文章:

java - 在 IntelliJ IDEA 中,测试如何访问正在测试的代码的 PSI 树结构?

html - 为什么图像上有不透明度如何在图像上设置不透明度并在 div 上设置悬停功能?

html - 在调整浏览器窗口/分辨率大小时保持元素位置

javascript - 在网站中延迟加载对讲脚本

java - Tomcat 找不到类 freemarker.template.TemplateException

java - 2个客户端之间通过服务器进行p2p连接

java - hibernate的hibernate.cache.use_structed_entries能做什么?

java - 尝试在 freemarker 中创建 min(a,b) 函数失败

java - 不关闭 stringwriter 会导致泄漏吗?

java - MD5 作为 Apache Camel 中的幂等 key