ジャンボモナカ

34歳のハゲデブがHTML5ハイブリッドアプリ開発プラットフォームmonacaを始めました。

thymeleafでテキストを表示

f:id:maipontan:20200510170227p:plain

Spring Bootとthymeleafでサーバー側で設定した変数の値をHTML内にテキストとして表示させたい。

まず、Spring Boot側でModelを用意する。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;


@SpringBootApplication
@Controller
public class HogeApplication {
    @GetMapping("/")
    public String top(Model model) {
        model.addAttribute("foo", "hello thymeleaf");
        return "top";
    }

}

html側

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div th:text="${foo}"></div>
</body>
</html>

デバッグすると、確かに、「hello thymeleaf」と表示された。

もう一捻りして、helloの部分をhtml側のテキストとして持たせたい場合は、「+」演算子で連結することができる。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;


@SpringBootApplication
@Controller
public class HogeApplication {
    @GetMapping("/")
    public String top(Model model) {
        model.addAttribute("foo", "thymeleaf");
        return "top";
    }

}

html側

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div th:text="'hello' + ${foo}"></div>
</body>
</html>