汎用テンプレートエンジン「FreeMarker」を使ってみる。
FreeMarkerは汎用テンプレートエンジンです。
- モデル + テンプレート → 出力
- モデルには任意のオブジェクトを指定可能。モデルのメソッドを呼び出した結果を出力することもできます。
- その他、基本的な制御構文(forやif)もサポート。
サンプル(文字列と数字の挿入)
テンプレート(./templates/test.ftl):
string : ${string} int : #{int}
メイン:
// コンフィグレーション Configuration cfg = new Configuration(); // テンプレート置き場を指定。 cfg.setDirectoryForTemplateLoading(new File("./templates")); // テンプレートを読み込み Template temp = cfg.getTemplate("test.ftl"); // データモデル Map root = new HashMap(); root.put("string", "string"); root.put("int", new Integer(100)); // テンプレート処理 Writer out = new OutputStreamWriter(System.out); // 標準出力に書く temp.process(root, out); out.flush();
出力:
string : string int : 100
サンプル2(メソッドの実行結果とループ)
テンプレート(./templates/object.ftl):
kittens: <#list kittens as k> ${k.name} : #{k.age} </#list> end
メイン:
/** * データモデル。 * クラスとメソッドはpublicでなければならない点に注意。 */ public static class Kitten { private String name; private int age; Kitten( String name, int age ) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } /** * テンプレートを処理する。 * @param args 引数 * @throws Exception */ public static void main ( String[] args ) throws Exception { // コンフィグレーション Configuration cfg = new Configuration(); // テンプレート置き場を指定。 cfg.setDirectoryForTemplateLoading(new File("./templates")); // テンプレートを読み込み Template temp = cfg.getTemplate("object.ftl"); // データモデル Map root = new HashMap(); root.put("kittens", Arrays.asList( new Kitten[]{ new Kitten( "mii", 2 ), new Kitten( "kuro", 1 ), new Kitten( "shiro", 1 ), new Kitten( "tora", 0 ) } )); // テンプレート処理 Writer out = new OutputStreamWriter(System.out); temp.process(root, out); out.flush(); }
出力:
kittens: mii : 2 kuro : 1 shiro : 1 tora : 0 end