Freemarker的使用方法


Freemarker是一个开源模板引擎,主要用于动态网页生成和邮件通知。它利用模板和变化的数据生成HTML或XML等任何文本输出。

一、Freemarker展示

通过预定义的XML或HTML模板,使用Freemarker引擎可以生成视图。其主要流程包括创建配置实例、加载模板、创建数据模型、处理模板和生成视图。

Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
cfg.setWrapUncheckedExceptions(true);
Template temp = cfg.getTemplate("test.ftl");
Map<String, Object> root = new HashMap<>();
root.put("user", "Big Joe");
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);

二、Freemarker的数据模型

在Freemarker中,数据模型就像一棵树,树的每个分支都可以是相应的Java对象。这些对象可以是简单的数字、字符串、日期、复杂的列表,甚至是哈希表。

Map<String, Object> root = new HashMap<>();
root.put("user", "Big Joe");
List<Product> productsList = new ArrayList<>();
productsList.add(new Product("product1", 2000));
productsList.add(new Product("product2", 3000));
root.put("products", productsList);

三、Freemarker中的指令

Freemarker模板不仅可以包含静态文本,还可以包含Freemarker标签,这就是我们常说的Freemarker指令。

举例来说,我们可以使用if指令来实现条件判断,foreach指令来循环处理数据。

<#if user?has_content>
    Hello, ${user}!
</#if>
<#list items as item>
    ${item_index+1}. ${item}
</#list>

评论关闭