kagamihogeの日記

kagamihogeの日記です。

Thymeleafさわる

テンプレートエンジンのThymeleafhello worldレベルのことをやる。

やることとしては、ローカルファイルにThymeleafを適用して出力を得る、までをやる。

環境

ソースコード

テンプレートファイル

テンプレートとなるsample.htmlC:\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を使用する。setPrefixsetSuffixに、適当なディレクトリとかサフィックスとかを指定する。

つぎに、テンプレートエンジンを作る。今回は使用するリゾルバをただ単に指定するだけ。

これで、ファイルを探してエンジンに適用する準備は整った。なので、つぎはテンプレートで置換したい値をエンジンに渡す準備をする。

置換したい値は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で指定するディレクトリの文字列の末尾にも区切り文字をつけないとダメだった。