網頁

2021/5/26

Spring Boot Thymeleaf 傳入頁面片段參數 fragment parameters

Spring Boot Thymeleaf 使用th:fragment定義頁面片段時可傳入參數。


參考「Spring Boot Thymeleaf 取代頁面片段」,下面依此進行修改。


例如在header.htmlth:fragment的名稱後加上參數feature,修改為th:fragment="header (feature)"

header.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
    <div th:fragment="header (feature)"><!-- 新增參數feature-->
        <h1>Thymeleaf <span th:text="${feature}"></span> Demo</h1>
    </div>
</body>
</html>

hello.html加入以上片段時,傳入${feature}變數。

hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Hello Thymeleaf</title>
</head>
<body>
    <div th:replace="~{logo}"></div>
    <div th:replace="~{header :: header (${feature})}">Header</div><!-- 傳入feature參數-->
    <div>
        <p th:text="'Hello, ' + ${name} + '!'"/>
    </div>
    <div th:replace="~{footer :: footer}">Footer</div>
</body>
</html>

在導向hello.htmlDemoController.hello()設定${feature}的來源屬性"feature"。

DemoController

package com.abc.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DemoController {

    @GetMapping("/hello")
    public String hello(
            @RequestParam(name = "name", required = false, defaultValue = "World") String name,
            Model model) {
        model.addAttribute("name", name);
        model.addAttribute("feature", "Parameterizable fragment signatures"); // 設定hello.html的${feaure}的值
        return "hello"; // forward to hello.html
    }
}

啟動專案後在瀏覽器輸入http://localhost:8080/demo/hello的回應如下。

<htmlv>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Hello Thymeleaf</title>
</head>
<body>
    <div><img src="spring.png"></div>
    <div>
        <h1>Thymeleaf <span>Parameterizable fragment signatures</span> Demo</h1>
    </div>
    <div>
        <p>Hello, World!</p>
    </div>
    <div>
        Copyright © 2014-2021 菜鳥工程師 肉豬 All rights reserved.
    </div>

</body>
</html>


沒有留言:

張貼留言