テンプレートエンジンのThymeleafでhello worldレベルのことをやる。
やることとしては、ローカルファイルにThymeleafを適用して出力を得る、までをやる。
環境
ソースコード
テンプレートファイル
テンプレートとなるsample.html
をC:\Java\sample.html
に置いておく。
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <body> <span th:text="${welcome}">variable expression value 1</span> <span th:text="${message.text}">variable expression value 2</span> </body> </html>
データを入れるクラス
後述。
package thymeleafsample.hoge; public class SampleMessage { public String getText() { return "kagamihoge"; } }
thymeleafを使うコード
package thymeleafsample.hoge; import java.io.FileNotFoundException; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import org.thymeleaf.templateresolver.FileTemplateResolver; public class HogeMain { public static void main(String[] args) throws FileNotFoundException { FileTemplateResolver resolver = new FileTemplateResolver(); resolver.setPrefix("C:\\Java\\"); resolver.setSuffix(".html"); TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(resolver); Context context = new Context(); SampleMessage message = new SampleMessage(); context.setVariable("welcome", "sdasdasdf"); context.setVariable("message", message); System.out.println(templateEngine.process("sample", context)); } }
まず、テンプレートファイルを探すためのリゾルバを作る。今回はローカルのファイルを探しに行くだけなので、リゾルバにはFileTemplateResolver
を使用する。setPrefix
とsetSuffix
に、適当なディレクトリとかサフィックスとかを指定する。
つぎに、テンプレートエンジンを作る。今回は使用するリゾルバをただ単に指定するだけ。
これで、ファイルを探してエンジンに適用する準備は整った。なので、つぎはテンプレートで置換したい値をエンジンに渡す準備をする。
置換したい値はContext
に入れる。今回はただ単にkey-valueを入れるだけなのでContext
を使う。
ちゃんとしたルールはドキュメントを参照してもらうとして。${welcome}
とcontext.setVariable("welcome", "sdasdasdf");
で、「テンプレートのwelcome変数はsdasdasdfを取得せよ」という意味合いになる。${message.text}
とcontext.setVariable("message", message);
で、「テンプレートのmessage.text変数はmessage.getText()を取得せよ」という意味合いになる。
で、process
の戻り値に実行結果が返ってくる。結果はこんな感じ。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <span>sdasdasdf</span> <span>kagamihoge</span> </body> </html>
ハマッたところ
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "sample", template might not exist or might not be accessible by any of the configured Template Resolvers
resolver.setPrefix("C:\\Java"); //NG resolver.setPrefix("C:\\Java\\"); //OK
今回のサンプルだと、setPrefix
で指定するディレクトリの文字列の末尾にも区切り文字をつけないとダメだった。