SpringBoot Thymeleaf 模板标签

扩展 Thymeleaf 模板标签

上一篇我们写到
SpringBoot 依赖之 Thymeleaf
模版引擎的使用,当时只列举了简单文本标签,下面针对多标签进行分析和分享。

Thymeleaf 的模板标签,包括文本显示、属性设置、条件判断、循环迭代、表单处理、片段引用、国际化支持等常用功能。我们尽可能的罗列出平时可能用到的模板标签。

1. 文本和变量

th:text

用于显示变量内容。

<p th:text="${name}">默认文本</p>
th:utext

用于显示未经转义的HTML内容。

<p th:utext="${htmlContent}">默认文本</p>

2. 属性设置

th:href

用于设置链接地址。

<a th:href="@{/home}">首页</a>
th:src

用于设置图片来源。

<img th:src="@{/images/ahauedu.png}" alt="logo">
th:attr

用于设置多个属性。

<a th:attr="href=@{/home}, title=#{home.title}">主页</a>
th:class / th:classappend / th:classprepend

用于设置或追加类名。

<div th:class="${condition} ? 'active' : 'inactive'"></div>
<div th:classappend="${condition} ? 'additional-class' : ''"></div>
<div th:classprepend="${condition} ? 'additional-class' : ''"></div>

3. 条件判断

th:if

用于条件渲染。

<p th:if="${user != null}">Welcome, <span th:text="${user.name}">User</span></p>
th:unless

用于条件渲染(取反)。

<p th:unless="${user != null}">请登录</p>

4. 循环迭代

th:each

用于迭代集合。

<ul>
    <li th:each="item : ${items}" th:text="${item.name}">Item Name</li>
</ul>
索引和状态变量
<ul>
    <li th:each="item, iterStat : ${items}" th:text="${iterStat.index} + ' - ' + ${item.name}"></li>
</ul>

5. 表单处理

th:actionth:object

用于表单的提交和绑定。

<form th:action="@{/submit}" th:object="${user}" method="post">
    <input type="text" th:field="*{name}" />
    <input type="password" th:field="*{password}" />
    <button type="submit">提交</button>
</form>
th:field

用于绑定表单字段。

<input type="text" th:field="*{name}" />

6. 片段引用

th:insertth:replace

用于插入或替换片段。

<div th:insert="~{fragments/header :: header}"></div>
<div th:replace="~{fragments/header :: header}"></div>
th:include

用于包含片段。

<div th:include="~{fragments/header :: header}"></div>

7. URL 参数

th:href

用于设置带有参数的 URL。

<a th:href="@{/user/view(id=${user.id})}">View User</a>

8. 列表选择

th:eachth:valueth:text 结合使用
<select th:field="*{country}">
    <option th:each="country : ${countries}"
            th:value="${country.code}"
            th:text="${country.name}">
    </option>
</select>

9. 属性替换

th:attr

用于替换任意属性。

<img th:attr="src=@{/images/cover.png}, alt=#{cover.alt}"/>

10. 切换属性

th:switchth:case

用于切换显示内容。

<div th:switch="${user.role}">
    <p th:case="'admin'">Admin Content</p>
    <p th:case="'user'">User Content</p>
    <p th:case="*">Default Content</p>
</div>

11. 日期和数字格式化

#dates.format#numbers.formatDecimal

用于格式化日期和数字。

<p th:text="${#dates.format(user.birthDate, 'dd-MM-yyyy')}"></p>
<p th:text="${#numbers.formatDecimal(user.salary, 2, 'POINT', 2, 'COMMA')}"></p>

12. 布尔属性

th:attr

用于设置布尔属性。

<input type="checkbox" th:attr="checked=${item.checked}"/>

示例项目结构

假设我们有一个简单的 Spring Boot 项目,其目录结构如下:
在这里插入图片描述

HomeController.java

package com.dependencies.thymeleaf.conroller;

import com.dependencies.thymeleaf.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Arrays;

/**
 * @author zhizhou   2024/7/26 22:33
 */
@Controller
public class HelloController {
    
    @GetMapping("/hello")
    public String index(Model model) {
        model.addAttribute("name", "Thymeleaf User");
        model.addAttribute("home", "http://www.thymeleaf.org");
    
        //<!--#### `th:unless`-->
        //<!--用于条件渲染(取反)。-->
        model.addAttribute("userinfo", null);
    
        //<!--### 3. 条件判断-->
        //<!--#### `th:if`-->
        //<!--用于条件渲染。-->
        User user = new User();
        user.setName("zhizhou");
        model.addAttribute("user", user);
        
        //<!--### 4. 循环迭代-->
        //<!--`th:each`-->
        //<!--用于迭代集合。-->
        model.addAttribute("users", Arrays.asList("zhizhou", "zhangsan", "lisi"));
        //<!-- 索引和状态变量-->
        model.addAttribute("userList", Arrays.asList(user, user, user));
        return "hello";
    }
}

hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Thymeleaf模版引擎示例</title>
</head>
<body>

<!--#### `th:src`-->
<!--用于设置图片来源。-->
<h3>th:src 用于设置图片来源</h3>
<img th:src="@{/images/ahauedu.jpg}" alt="Logo">
<p>-------------------------------------------------</p>

<!--### 1. 文本替换-->
<h3>th:text 文本替换</h3>
<h1 th:text="'Hello, ' + ${name} + '!'">Hello, World!</h1>
<p>-------------------------------------------------</p>

<h3>th:insert 片段引入</h3>
<div th:insert="~{frame :: header}"></div>
<p>-------------------------------------------------</p>
<!--<p th:text="${name}">Default Text</p>-->

<!--### 2. 属性设置-->
<!--#### `th:href`-->
<!--用于设置链接地址。-->
<h3>th:href 用于设置链接地址</h3>
<a th:href="@{/home}">Home</a>
<p>-------------------------------------------------</p>


<!--### 3. 条件判断-->
<!--#### `th:if`-->
<!--用于条件渲染。-->
<h3>th:if 条件判断</h3>
<p th:if="${user != null}">Welcome, <span th:text="${user.name}">用户名</span></p>
<p>-------------------------------------------------</p>

<!--#### `th:unless`-->
<!--用于条件渲染(取反)。-->
<h3>th:unless 用于条件渲染(取反)</h3>
<p th:unless="${userinfo != null}">请登录</p>
<p>-------------------------------------------------</p>

<!--### 4. 循环迭代-->
<!--`th:each`-->
<!--用于迭代集合。-->
<h3>th:each 循环迭代</h3>
<ul>
  <li th:each="user : ${users}" th:text="${user}">用户名</li>
</ul>
<p>-------------------------------------------------</p>

<!-- 索引和状态变量-->
<h3>索引和状态变量</h3>
<ul>
  <li th:each="user, iterStat : ${userList}" th:text="${iterStat.index} + ' - ' + ${user.name}"></li>
</ul>
<p>-------------------------------------------------</p>

<p th:text="#{welcome.message}">Welcome!</p>
</body>
</html>

frame.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="header">
    <h1>外部碎片信息</h1>
</div>
</body>
</html>

在这里插入图片描述

通过以上配置和示例,我们可以快速上手并使用 Thymeleaf 模板引擎来构建动态 Web 应用程序。Thymeleaf 提供的丰富标签和功能可以帮助你轻松实现复杂的视图逻辑。如果对你有点点用,请点点你的大拇指👍🏻,是对我最大的鼓励和认可,非常感谢。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot Thymeleaf项目是使用Spring Boot框架和Thymeleaf模板引擎来构建的。在配置Spring Boot Thymeleaf项目时,需要进行以下几个步骤: 1. 在pom.xml文件中引入Thymeleaf依赖。可以使用以下代码片段将Thymeleaf依赖添加到pom.xml文件中: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 这将确保项目中包含Thymeleaf所需的所有依赖项。\[2\] 2. 在application.properties或application.yml文件中添加Thymeleaf的配置。可以使用以下代码片段来配置Thymeleaf的相关属性: ``` spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.cache=false spring.thymeleaf.suffix=.html spring.thymeleaf.servlet.content-type=text/html ``` 这些配置将指定Thymeleaf模板文件的位置、编码方式、缓存设置等。\[1\] 3. 在项目中使用Thymeleaf模板引擎来创建和渲染页面。可以使用Thymeleaf的语法和标签来编写动态的HTML页面。在Spring Boot中,可以将Thymeleaf模板文件放置在src/main/resources/templates目录下,并使用@Controller注解的控制器类来处理请求并返回Thymeleaf模板。\[1\] 通过以上步骤,你就可以开始使用Spring Boot和Thymeleaf来构建动态的Web应用程序了。 #### 引用[.reference_title] - *1* *2* [springBoot整合thymeleaf(超简单)](https://blog.csdn.net/baobei_ll/article/details/124213027)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [springboot中使用thymeleaf](https://blog.csdn.net/qq_41378597/article/details/85644813)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值