Apache Freemarker的循环示例

虽然现在有点晚了,但最近我有机会使用Apache FreeMarker。那时候,我找不到使用Map进行循环输出的日语示例,所以就顺手记录了一个示例。

前提 tí)

Apache FreeMarker:2.3.28
阿帕奇FreeMarker:2.3.28

输出结果 (Shū chū

这次我们将使用FreeMarker将HTML进行输出。
输出结果如下图所示。

result.png

中国龙舞

  <dependencies>
    <!-- FreeMarker -->
    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.28</version>
    </dependency>
  </dependencies>

模板

模板将保存在[src/main/resource/template.html]中。
表格标签的tr标签,以及表格标签下的

以下是用于将列表或映射重复输出为标签的设置。

[来自列表的表格]

<#list itemList as item></#list>

参数 数值 注释
${item.param} ${item.value} ${item.comment}

[来自映射的数值]

<#list mapValue as key, value>

${key}:${value}

</#list>

Java

源代码将按部分进行编写。

模板参数

以下是为传递给 FreeMarker 的参数(可变值)的编码。

//====== 构建模板参数 ======//
Map<String, Object> paramMap = new HashMap<>();

// 构建 itemList
List<Map<String, String>> itemList = new ArrayList<>();
Map<String, String> itemMap1 = new HashMap<>();
itemMap1.put(“param”, “param1”);
itemMap1.put(“value”, “99.1”);
itemMap1.put(“comment”, “hogehoge”);
itemList.add(itemMap1);
Map<String, String> itemMap2 = new HashMap<>();
itemMap2.put(“param”, “param2”);
itemMap2.put(“value”, “98.2”);
itemMap2.put(“comment”, “hogehoge2”);
itemList.add(itemMap2);
paramMap.put(“itemList”, itemList);

// 构建 mapValue
Map<String, String> mapValue = new HashMap<>();
mapValue.put(“param3”, “97.3”);
mapValue.put(“param4”, “96.4”);
paramMap.put(“mapValue”, mapValue);

由于源代码中 Map 的内容不易理解,因此附上了 [paramMap] 调用 toString() 的结果。

paramMap
{
itemList=[
{param=param1, value=99.1, comment=hogehoge},
{param=param2, value=98.2, comment=hogehoge2}
],
mapValue={
param3=97.3,
param4=96.4
}
}

输出

FreeMarker 模板的初始化和输出处理如下。
输出结果会同时输出到标准输出和文件(result.html)中。

//====== 初始化模板 ======//
// 新建 Config
Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);

// 编码设置
cfg.setDefaultEncoding(“UTF-8”);

// 设置模板路径
cfg.setClassLoaderForTemplateLoading(Thread.currentThread().getContextClassLoader(), “/”);

//====== 输出 ======//
try {

// 获取模板
Template template = cfg.getTemplate(“template.html”);

// 写入系统输出
Writer out = new OutputStreamWriter(System.out);
template.process(paramMap, out);
out.flush();

// 写入文件
try (Writer fw = new FileWriter(new File(“result.html”))) {
template.process(paramMap, fw);
out.flush();
}

} catch(IOException | TemplateException ex) {
ex.printStackTrace();
System.exit(1);
}

Git

请参考 GitHub 上的所有源代码。

广告
将在 10 秒后关闭
bannerAds