0
点赞
收藏
分享

微信扫一扫

Thymeleaf学习笔记

夕阳孤草 2022-01-12 阅读 100

Thymeleaf

一、概述

  1. 是一个现代的服务器端的Java模板引擎,适用于Web和独立环境
  2. SpringBoot官方推荐的模板引擎

二、工作原理

在这里插入图片描述

三、快速入门

1. 实现步骤

  1. 导入依赖
  2. 配置文件
  3. 写Controller
  4. 模板文件

2. 具体操作

2.1 导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.2 配置文件

spring:
  thymeleaf:
    #关闭缓存
    cache: false
    #检查
    check-template: true

2.3 写controller

@Controller
@RequestMapping("/thymeleaf")
@Slf4j
public class ThymeleafController {

    @RequestMapping("/test01")
    public String test1(Model model){
        model.addAttribute("name", "张三");
        return "success";
    }

}

2.4 模板文件

resources下-templates下-html文件

<p th:text=“${name}”>小强</p>

四、配置

请添加图片描述

五、常用指令

1. th:text

model.addAttribute("name", "张三");

模板文件

<p th:text="${name}">xxx</p>
model.addAttribute("age", 18);

模板文件

<h2 th:text="${age >= 18 ? '成年人' : '未成年人'}"></h2>
<h3 th:text="|姓名:${name},性别:${age}|"></h3>

2. th:utext

model.addAttribute("content", "<h1>这是一个h1标题</h1>");

模板文件

<span th:utext="${content}"></span>

3. th:if th:unless

<h4 th:if="${age >= 18}">年龄到达18岁,允许进入该网站</h4>

<h4 th:unless="${age >= 18}">年龄没有到达18岁,多吃点,快点长大</h4>

4. th:each

List<Employee> emps = employeeMapper.findAllAndDept();

model.addAttribute("emps", emps);

模板文件

<table border="1" cellpadding="10" cellspacing="0">
        <tr>
            <th>row</th>
            <th>id</th>
            <th>empName</th>
            <th>birthday</th>
            <th>salary</th>
            <th>dept</th>
        </tr>
        <!-- 
            th:each="迭代的元素,状态变量 : ${集合数据}"
         -->
        <tr th:each="emp,empStat : ${emps}">
            <th th:text="${empStat.index + 1}">id</th>
            <th th:text="${emp.id}">id</th>
            <th th:text="${emp.empName}">empName</th>
            <!--
                #xxx : 代表thymeleaf的内置对象
                dates : 用来操作时间
                    format : 格式化
                        参数1:要操作的时间
                        参数2:要显示的时间格式
            -->
            <th th:text="${#dates.format(emp.birthday, 'yyyy-MM-dd')}">birthday</th>
            <!--
                numbers : 用来操作数值
                    formatDecimal : 格式化
                        参数1:要操作的数值
                        参数2:要保留的整数位,如果0,代表不对整数操作
                        参数3:要保留的小数位
            -->
            <th th:text="${#numbers.formatDecimal(emp.salary/100.0, 0, 2)}">salary</th>
            <th th:text="${emp.department.deptName}">dept</th>
        </tr>
    </table>

5. th:inline

模板文件

<body>
	<button onclick="getName()">获取模型数据的name</button>
</body>
<!-- 在js中使用thymeleaf -->
<script th:inline="javascript">
    function getName() {
        alert([[${name}]]);
    }
</script>
举报

相关推荐

0 条评论