Thymeleaf基本使用,全靠我啃烂了这份2021最新面试题

org.springframework.boot

spring-boot-starter-thymeleaf

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

org.springframework.boot

spring-boot-maven-plugin

Thymeleaf默认会开启页面缓存,提高页面并发能力。但会导致我们修改页面不会立即被展现,因此我们关闭缓存。

关闭Thymeleaf的缓存

spring:

thymeleaf:

cache:

false

另外,修改完毕页面,需要使用快捷键:Ctrl + Shift + F9来刷新工程。

在这里插入图片描述

快速入门


我们准备一个controller,控制视图跳转:

@Controller

public class HelloController {

@GetMapping(“hello”)

public String show1(Model model){

model.addAttribute(“msg”, “Hello, Thymeleaf!”);

return “index”;

}

}

新建一个html模板:

语法说明:

Thymeleaf通过${}来获取model中的变量,注意这不是el表达式,而是ognl表达式,但是语法非常像。不过区别在于,我们的表达式写在一个名为:th:text的标签属性中,这个叫做指令

hello

大家好

启动项目,访问页面:

在这里插入图片描述

动静结合:

Thymeleaf崇尚自然模板,意思就是模板是纯正的html代码,脱离模板引擎,在纯静态环境也可以直接运行。现在如果我们直接在html中编写 ${}这样的表达式,显然在静态环境下就会出错,这不符合Thymeleaf的理念。

Thymeleaf中所有的表达式都需要写在指令中,指令是HTML5中的自定义属性,在Thymeleaf中所有指令都是以th:开头。因为表达式${user.name}是写在自定义属性中,因此在静态环境下,表达式的内容会被当做是普通字符串,浏览器会自动忽略这些指令,这样就不会报错了!

th常用标签


| 标签 | 作用 | 样例 |

| — | — | — |

| th:id | 替换id | <input th:id="${user.id}"/> |

| th:text | 文本替换 | <p text:="${user.name}">name</p> |

| th:utext | 支持html的文本替换 | <p utext:="${htmlcontent}">content</p> |

| th:object | 替换对象 | <div th:object="${user}"></div> |

| th:value | 属性赋值 | <input th:value="${user.name}" > |

| th:with | 变量赋值运算 | <div th:with="isEven=${user.age}%2==0"></div> |

| th:style | 设置样式 | th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''" |

| th:src | 替换资源 | <script type="text/javascript" th:src="@{index.js}"></script> |

| th:onclick | 点击事件 | th:onclick="'getCollect()'" |

| th:href | 替换超链接 | <a th:href="@{index.ht

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值