LoginSignup
7
0

はじめに

初めまして、今回は以前現場で使っていた技術を備忘録的に記事にまとめようと思います。

Thymeleaf(タイムリーフ)とは

ThymeleafとはJavaのテンプレートエンジンの一種で、SpringBootアプリケーションを開発する際によく利用されます。
HTMLファイルに独自のタグを使用せずに利用できるため、そのままブラウザで表示することが可能です。

テンプレートエンジンとは

テンプレート部分と動的データ部分を合成し、成果ドキュメントを出力する機能です。
デザイン部分とロジック部分を切り離して作業できるといった利点があることから重宝されています。

環境

Windows 10 Home
SpringToolSuite4
JavaSE-17

実装

プロジェクト構成ファイルに依存関係を追加

gradle.build
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

HTMLファイルに適用

テンプレートとなるHTMLファイルのhtmlタグに以下を入れる。(例:index.html)

index.html
<html xmlns:th="http://www.thymeleaf.org">

Controllerの作成

HelloController.java
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        model.addAttribute("message", "変数式を表示");
        return "index";
    }
}

htmlのタグにth:text属性(Thymeleafで扱う属性)を設定

index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <h1>Thymeleaf sample</h1>
    <p>
      <span th:text="${message}"/>
    </p>
  </body>
</html>

構文

Thymeleafの基本は以下の構造となります。

th:属性=式

属性

・text
→値の表示

・utext
→値の表示(エスケープ処理なし)

・if
→式がtrueの時のみ出力

・each
→配列等をループ出力

...他

・単純式
変数式:${...}
→変数やプロパティの値を表示

選択変数式:*{...}
→オブジェクト中のプロパティを取得

メッセージ式:#{...}
→プロパティファイルに記述したメッセージを表示

リンクURL式:@{...}
→リンクやリダイレクトのURLを生成

フラグメント式: ~{...}
→マークアップのフラグメントを指定、テンプレート内でフラグメントを移動

・リテラル
テキストリテラル:'one text', 'Another one!',…
数値リテラル:0, 34, 3.0, 12.3,…
真偽値リテラル:true, false
Nullリテラル:null
リテラルトークン:one, sometext, main,…

・テキスト演算
文字列結合:+
リテラル置換:|The name is ${name}|

・算術演算
二項演算子:+, -, *, /, %
マイナス符号(単項演算子):-

・論理演算
二項演算子:and, or
論理否定演算子(単項演算子):!, not

・比較と等価
比較演算子:>, <, >=, <= (gt, lt, ge, le)
等価演算子:==, != (eq, ne)

・条件演算子
If-then:(if) ? (then)
If-then-else:(if) ? (then) : (else)
デフォルト:(value) ?: (defaultvalue)

・特別なトークン
処理なし:_

最低限の構成で実行

SpringBootアプリケーションを実行します。
Controllerで設定したmessageの中身が、html内のth:text="${message}"部に代入され以下のような表示となります。
image.png

色々設定してみた

index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <h1>Thymeleaf sample</h1>
    <p th:if="#{bool.true}">
      <span th:text="${trueMessage}"/>
    </p>
    <p th:if="#{bool.false}">
      <span th:text="${fasleMessage}"/>
    </p>
	<p th:each="each : ${list}">
	    <span th:text="${each}"/>
	</p>
  </body>
</html>
HelloController.java
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
    	String[] StrList = {"配列の","表示","確認"};
        model.addAttribute("trueMessage", "設定ファイルがtrueなので表示される文言");
        model.addAttribute("falseMessage", "設定ファイルがfalseなので表示されない文言");
        model.addAttribute("list", StrList);
        return "index";
    }
}

image.png

プロパティに定義されたboolによって表示を切り替えたり配列を扱うこともできました。

参考資料

7
0
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
7
0