1 Thymeleaf常见属性

先来说说Thymeleaf常见的属性

1 th:action 定义后台控制器的路径,类似<form>标签的 action 属性,主要结合 URL 表达式,获取动态变量

2 th:method 设置请求方法<form id="login" th:action="@{/login}" th:method="post">......</form>

3 th:href  定义超链接,主要结合 URL 表达式,获取动态变量

4 th:src  用于外部资源引入,比如<script>标签的 src 属性,<img>标签的 src 属性,常与@{}表达式结合使用,在 SpringBoot 项目的静态资源都放到 resources 的 static 目录下。
放到 static 路径下的内容,写路径时不需要写上 static

5 th:id  类似 html 标签中的 id 属性<span th:id="${hello}">aaa</span>

6 th:name 设置名称 <input th:type="text" th:id="userName" th:name="userName">类似 html 标签中的 value 属性,能对某元素的 value 属性进行赋值<input type="hidden" id="userId" name="userId" th:value="${userId}">

7 th:attr 该属性也是用于给 HTML 中某元素的某属性赋值,好处是可以给 html 中没有定义的属性动态的赋值

8 th:text 用于文本的显示,该属性显示的文本在标签体中,如果是文本框,数据会在文本框外显示,要想显示在文本框内,使用 th:value

<input type="text" id="realName" name="reaName" th:text="${realName}">

9 th:object 用于数据对象绑定通常用于选择变量表达式(星号表达式)

10 th:onclick  目前 thymeleaf 版本要求只能传递数字和布尔值<a th:οnclick="'show('+${user.id}+')'">点击:显示学生编号</a>

11 th:style 设置样式  <a th:οnclick="'show('+${user.id}+')'" 
th:style="'font-size:40px;color:red;'">点击:显示学生编号</a>

 2 Thymeleaf条件判断th:if、th:unless、th:switch、th:case

controller类

package com.liuhaiyang.springboot.controller;

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

@Controller
public class UserController {
    @RequestMapping("/condition")
    public String condition(Model model){
        model.addAttribute("sex",1);
        model.addAttribute("flag",true);
        model.addAttribute("productType",0);
        return "condition";
    }
}

前端数据展示页面(condition.xml)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>条件判断</title>
</head>
<body>
<h1>th:if 用法:如果满足条件显示(执行),否则相反</h1>
<div th:if="${sex eq 1}"> 男</div>
<div th:if="${sex eq 0}"> 女</div>

<h1>th:unless 语法:与th:if用法相反,即条件判断取反</h1>
<div th:unless="${sex ne 1}">女</div>

<h1>th:switch/th:case用法</h1>
<div th:switch="${productType}">
    <span th:case="0">产品0</span>
    <span th:case="1">产品1</span>
    <span th:case="*">无此产品</span>
</div>
</body>
</html>

核心配置文件

spring.thymeleaf.cache=false

启动入口类展示结果

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐