[Spring]Thymeleaf——XML/XHTML/HTML5模板引擎

12 篇文章 1 订阅

什么是Thymeleaf?

Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
官方文档


使用

Maven依赖

<!--thymeleaf启动器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

application.yml配置

  • cache : 设置thymeleaf的缓存。默认true,用于测试。
  • encoding : 编码
  • prefix : classpath:/templates/,模板文件路径
spring:
  thymeleaf:
    cache: false
    encoding: UTF-8

创建html

在resources/templates/目录中创建xxx.html。
这里创建了hello.html。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>
<body>
	<!--输出内容,${key}是替换的变量-->
	<div th:text="${key}"></div>
</body>
</html>

Controller返回页面

@Controller
@RequestMapping("/test")
public class TestController {

    /**
    * 访问test/hello,返回hello.html
    */
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("key","hello world");
        return "hello";
    }
}

常用标签

标签作用
th:id替换id
th:text文本替换
th:utext支持html的文本替换
th:object替换对象
th:value替换值
th:each迭代
th:href替换超链接
th:src替换资源

取值

${Key}

循环
<ul th:each="item:${MyList}">
    <li th:text="${item}"></li>
</ul>

引入资源

@{资源地址}

读取配置文件中数据

#{key}

引用公共页面

  • th:insert:将代码块片段整个插入到使用了 th:insert 属性的 HTML 标签中;
  • th:replace:将代码块片段整个替换使用了 th:replace 属性的 HTML 标签中;
  • th:include:将代码块片段包含的内容插入到使用了 th:include 属性的 HTML 标签中。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码鹿的笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值