m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

JavaのFreeMakerでテンプレート処理を行う2

インクルード処理を使う

1つのテンプレートの中に他のテンプレートファイルを読み込みます。

pom.xml

  <dependencies>
    
    <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.23</version>
    </dependency>

  </dependencies>
ml|

テンプレートファイル

sample2.ftl
<#-- header -->
<#include "parts/header.ftl">

<#-- contents -->
${contents}

<#-- footer -->
<#include "parts/footer.ftl">
parts/header.ftl
----------------------
header情報です。
----------------------
${header}
parts/footer.ftl
----------------------
footer情報です。
----------------------
${footer}

実装

Sample02.java
package com.example;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Sample02 {

	public static void main(String[] args) throws IOException, TemplateException {
		
		// 初期化
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
		
		// ディレクトリを指定
		cfg.setDirectoryForTemplateLoading(new File("src/main/resources/template"));
		
		// テンプレートファイルを指定
		Template temp = cfg.getTemplate("sample2.ftl");
		
		// データモデル
		Map<String, String> root = new HashMap<String, String>();
		root.put("header", "ヘッダーのデータを表示中");
		root.put("contents", "テストデータです。");
		root.put("footer", "フッターのデータを表示中");
		
		// テンプレート処理
		Writer out = new StringWriter();
		temp.process(root, out);
		out.flush();
		
		// 結果出力
		String displayStr = out.toString();
		System.out.print(displayStr);
	}
}

※ヘッダー、フッターのものも一緒に定義する必要がある。

header情報です。
----------------------
ヘッダーのデータを表示中

テストデータです。

----------------------
footer情報です。
----------------------
フッターのデータを表示中

うん、想定どおりで安心しました。

今回はここまで…