- JSP
- Velocity
- FreeMarker
最近だと以下の様なのあるようです。
- Thymeleaf
- 所見:コーダーさんが用意してくれるhtmlをほぼ変更せずにテンプレートエンジンを適用できるような感じ。
- Mustache
- 所見:「ますたっしゅ」って呼ぶそうです。Ruby、Java、Python、Javascript、node.js、... と多くの言語をサポート。使い方がシンプル。
まずはテンプレートは以下の様なものを用意しました。
<!DOCTYPE html> <html> <head> <title>Mustache</title> <meta charset="UTF-8"> </head> <body> {{!This is comment of Mustache!!}} <h1>pojo.str</h1> <h2>{{str}}</h2> <h1>pojo.num</h1> <h2>{{num}}</h2> <h1>pojo.flag</h1> {{#flag}}flag = true {{/flag}} {{^flag}}flag = false {{/flag}} <h1>pojo.array</h1> {{#array}} {{.}}</br> {{/array}} <h1>pojo.data</h1> {{#data}} <p>upper: {{a}} , {{b}}</p></br> {{/data}} <h1>Escaped Characters</h1> {{escape}} </body> </html> </html>
{{ }} で囲われたところにデータで埋め込まれます。{{#xxx}}〜{{/xxx}}が配列データの繰り返しです。囲われたデータにアクセスする際は、{{.}}とドットでアクセスします。またMapデータのようなkey-valueは、{{key}}でvalue要素にアクセスします。
でJavaは以下のように用意してみました。
package com.blogspot.agiroh.netty.template.html; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; public class ExampleMustache { final static String template_path = "template/mustache/example.mustache"; public static class ExamplePojo { String str; long num; boolean flag; Map<String, Object> data; List<String> array; String escape; } static Map<String, Mustache> templates = new HashMap<>(); public void run() throws Exception { MustacheFactory factory = new DefaultMustacheFactory(); // default is classpath root Mustache mustache = null; if ( !templates.containsKey(template_path)) { mustache = factory.compile(template_path); templates.put(template_path, mustache); } else { System.out.println("templates from cache"); mustache = templates.get(template_path); } ExamplePojo pojo = new ExamplePojo(); pojo.str = UUID.randomUUID().toString(); pojo.num = new Date().getTime()/1000; pojo.flag = true; pojo.data = new HashMap<String, Object>(); pojo.data.put("a", "A"); pojo.data.put("b", "B"); pojo.array = new ArrayList<>(); pojo.array.add("hoge"); pojo.array.add("fuga"); pojo.escape = "<p>\"te&st\"</p>"; mustache.execute( new PrintWriter(System.out), pojo).flush(); } public static void main(String[] args) { try { new ExampleMustache().run(); } catch (Exception e) { e.printStackTrace(); } } }
結果は以下になります。きちんとhtmlのエスケープ処理もされています。なかなか使いやすいとおもいますがいかがでしょうか。
<!DOCTYPE html> <html> <head> <title>Mustache</title> <meta charset="UTF-8"> </head> <body> <h1>pojo.str</h1> <h2>5b954508-cf30-4501-b173-75a33446e4ba</h2> <h1>pojo.num</h1> <h2>1362906356</h2> <h1>pojo.flag</h1> flag = true <h1>pojo.array</h1> hoge</br> fuga</br> <h1>pojo.data</h1> <p>upper: A , B</p></br> <h1>Escaped Characters</h1> <p>"te&st"</p> </body> </html> </html>
0 件のコメント:
コメントを投稿