Thymeleafテンプレートエンジンを単体で使う(Thymeleaf 3版)
これは何
m12i.hatenablog.com このサイトの Thymeleaf 3版 です。要はSpringを使わずに、Thymeleaf 3 だけを使ってhtmlファイルを書きだすサンプルです。
参考
Thymeleaf 3ドキュメントの日本語版ページも確認しました。 www.thymeleaf.org
翻訳していただき、ありがとうございます。
バージョン情報
- Java 11
- Thymeleaf 3.0.11
ディレクトリ構造
src └ main ├ java │ └ sample │ └ Main.java └ resource └ sample.html
Javaソース
参考にさせていただいたソースとの差異は以下の通り。
- org.thymeleaf.context.VariablesMap と org.thymeleaf.templateresolver.TemplateResolver が削除されている。
- VariablesMap は使わずに、ContextクラスのsetVariableを直で呼び出している。
- TemplateResolver は ClassLoaderTemplateResolver を直で使うようにした。
Javaソースはこちら。
package sample; import java.io.FileWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Calendar; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import org.thymeleaf.context.IContext; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; public class Main { public void execute(String... args) throws Exception { // テンプレートエンジンを初期化する final TemplateEngine engine = initializeTemplateEngine(); // コンテキストを生成する final IContext ctx = makeContext(args); // 今回はWriter経由で結果を出力するのでWriterも初期化 final Writer writer = new FileWriter("sample.html"); // テンプレート名とコンテキストとWriterを引数としてprocessメソッドをコール engine.process("sample", ctx, writer); // Writerをクローズ writer.close(); } private TemplateEngine initializeTemplateEngine() { // エンジンをインスタンス化 final TemplateEngine templateEngine = new TemplateEngine(); // テンプレート解決子をインスタンス化(今回はクラスパスからテンプレートをロードする) final ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); // テンプレートモードはXHTML resolver.setTemplateMode("XHTML"); // クラスパスのtemplatesディレクトリ配下にテンプレートファイルを置くことにする resolver.setPrefix("templates/"); // テンプレートの拡張子はhtml resolver.setSuffix(".html"); // テンプレート解決子をエンジンに設定 templateEngine.setTemplateResolver(resolver); return templateEngine; } private IContext makeContext(String... args) { final IContext ctx = new Context(); // 変数マップにテンプレート変数を設定 String[] values = {"aaa", "bbb"}; ((Context) ctx).setVariable("args", values); //公式ガイドの日本語訳がこれだったのでそのままコピーした… SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy"); Calendar cal = Calendar.getInstance(); ((Context) ctx).setVariable("today", dateFormat.format(cal.getTime())); return ctx; } public static void main(String... args) throws Exception { new Main().execute(args); } }
htmlソースはこちら。
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xml:lang="ja" lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Sample</title> </head> <body> <h1>Arguments</h1> <p> The sample application received <span th:text="${#arrays.isEmpty(args)} ? 'no' : 'some'">...</span> arguments. </p> <p>Today is: <span th:text="${today}">13 February 2011</span></p> <ul> <li th:each="a : ${args}"><span th:text="${a}">...</span></li> </ul> </body> </html>
これで動かすと、プロジェクト直下にsample.html が生成される。
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Sample</title> </head> <body> <h1>Arguments</h1> <p> The sample application received <span>some</span> arguments. </p> <p>Today is: <span>22 2月 2019</span></p> <ul> <li><span>aaa</span></li> <li><span>bbb</span></li> </ul> </body> </html>