LoginSignup
0
1

More than 1 year has passed since last update.

Spring Boot勉強③ Thymeleafの使い方

Posted at

はじめに

https://qiita.com/fattolys/items/9567a412bf1703948731
前回の続き

ThymeleafでHello Worldを表示したけど、どうやって?HTMLでの表現方法?について調べてみた

目次

  1. 表示の仕組み
  2. 表現方法
  3. 参考文献

表示の仕組み

HelloWorldController.java
/*ここまで省略*/
@Controller
public class HelloWorldController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!!");
        return "index";
    }
}
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <h1>任意タイトル</h1>
    <h2><span th:text="${message}"></span></h2>
  </body>
</html>

上記構成の場合、HelloWorldController.javaでは

HelloWorldController.java
        model.addAttribute("message", "Hello World");

にてテンプレート(HTML)に渡す変数("message")を model.addAttribute で登録している
その後、

HelloWorldController.java
        return "index";

で戻り値に表示するHTMLのテンプレートファイル名(index)を指定

index.htmlでは、

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

htmlタグに上記を記載し、Thymeleaf のテンプレートであることを明示

index.html
<span th:text="${message}"></span>

上記でControllerで設定した変数("message")を指定することでHTMLとしては以下のように解釈される

index.html
<span Hello World></span>

表現方法

TBD

参考文献

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