S-JIS[2015-05-05/2015-05-06] 変更履歴

FreeMarker

FreeMarkerは、Javaで使えるテンプレートエンジン。


インストール

Gradleを使ったプロジェクトの場合、build.gradleのdependenciesにFreeMarkerを追加する。

build.gradle:

apply plugin: 'java'
apply plugin: 'eclipse'

group = 'example'
version = '0.1-SNAPSHOT'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
	mavenCentral()
}

dependencies {
	compile group: 'org.freemarker', name : 'freemarker', version: '2.3.22'
	testCompile 'junit:junit:4.11'
}

eclipse.classpath.file {
	whenMerged { classpath ->
		classpath.entries.findAll { entry -> entry.kind == 'output' }*.path = 'classes'
	}
}

で、Gradleのeclipseタスクを実行すれば、EclipseのプロジェクトにFreeMarkerのライブラリーが入る。

> gradle eclipse

FreeMarkerを試してみる。


まず、テンプレートファイルを作成する。(UTF-8を想定)

src/main/templates/example.ftl:

<#-- テスト -->
テスト: ${hoge}

テンプレートを使うクラスを作成する。

src/main/java/com/example/freemarker/Example.java:

package com.example.freemarker;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
//import freemarker.template.Version;
public class Example {

	public static void main(String... args) throws IOException, TemplateException {
//		Configuration cfg = new Configuration(new Version("2.3.22"));
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);

		Path srcPath = Paths.get("D:/workspace/freeMarker/src/main/templates");
		cfg.setDirectoryForTemplateLoading(srcPath.toFile());
		cfg.setDefaultEncoding("UTF-8");

		Template template = cfg.getTemplate("example.ftl");

		// データモデルを定義
		Map<String, Object> dataModel = new HashMap<>();
		dataModel.put("hoge", "ほげ");

		// テンプレート処理
		Path dstPath = Paths.get("D:/tmp/freeMarker/example.txt");
		Files.createDirectories(dstPath.getParent());
		try (Writer writer = Files.newBufferedWriter(dstPath, StandardCharsets.UTF_8)) {
			template.process(dataModel, writer);
		}
	}
}

最初にConfigurationを生成し、テンプレートファイルのルートディレクトリーを指定する。
そして、Configuration#getTemplate()でテンプレートファイルを指定する。
Configuration#setDefaultEncoding()は、テンプレートファイルの(デフォルトの)エンコーディングを指定するもの。
(ちなみに、Configurationはシングルトンで使うものらしく、キャッシュが失われるので再作成せずに使い回すようだ。一度設定したら、後は読み込むだけなので、スレッドセーフで使えるらしい)

テンプレートに出力する可変データは、FreeMarkerではデータモデルと呼ぶらしい。
Mapを使うのがとりあえず一番簡単だが、JavaBeansやList、TemplateModelインターフェースを継承した各種クラスが使えるようだ。

Template#process()でデータモデルを使ってWriterに出力する。


出力結果:

テスト: ほげ

テンプレートファイル上で${hoge}だった部分が、プログラム内で指定した値に変わっている。


Javaへ戻る / 技術メモへ戻る
メールの送信先:ひしだま