LoginSignup
3
1

More than 3 years have passed since last update.

【Java】Thymeleaf基本 (SpringBoot)

Last updated at Posted at 2020-10-25

Thymeleafとは

  • SpringBootで標準で使われるテンプレートエンジン
  • テンプレートエンジンを使うことでWebアプリケーション(MPA)を作るのに必要な機能が追加される
  • 例えばHTMLファイルの中に[[]]でJavaの変数名[[${modelValue}]]を書くことができる
  • これで画面が表示される時に、HTMLファイルがテンプレートとなって、Placefolder(=置き換わる場所)をSpringフレームワークが書き換えてくれる
  • テンプレートの機能を果たすものをThymeleafという timeleaf.png

使用方法

  • build.gradleファイルのdependenciesにThymeleafが定義がされていることを確認
dependencies {
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
}

テンプレートファイルの呼び出し

  • デフォルト設定では/resources/templates/【Controller の戻り値】.html 配下にテンプレートファイルを記述
  • 以下の例はMain.javaでHelloControllerを呼び出し、クラスパス以下のテンプレートファイルが探索されsrc/main/resources/templates/hello.html がテンプレートファイルとして利用される。
main.java
package sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}
HelloController.java
package sample.thymeleaf.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello Thymeleaf!!");
        return "hello";
    }
}
hello.html
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
        <title>Hello Thymeleaf</title>
    </head>
    <body>
        <h1 th:text="${message}"></h1>
    </body>
</html>

テンプレートファイルでテキストを埋め込み

  • th:text=【出力する値】そのタグのテキスト要素を出力
  • <h1 th:text="'hello world'"></h1>
  • <h1>[['hello world!!']]</h1> で直接テンプレート上に値を出力することもできる
HelloController.java
package sample.thymeleaf.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}
hello.html
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
        <title>Hello Thymeleaf</title>
    </head>
    <body>
        <h1 th:text="'hello world'"></h1>
    </body>
</html>
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1