Thymeleaf学习笔记

Thymeleaf 模板引擎

1、Thymeleaf 是 Web 和独立环境的现代服务器端 Java 模板引擎,能够处理HTML,XML,JavaScript,CSS 甚至纯文本。

2、Thymeleaf 的主要目标是提供一种优雅和高度可维护的创建模板的方式。为了实现这一点,它建立在自然模板的概念上,将其逻辑注入到模板文件中,不会影响模板被用作设计原型。这改善了设计的沟通,弥补了设计和开发团队之间的差距。

3、Thymeleaf 也从一开始就设计了Web标准 - 特别是 HTML5 - 允许您创建完全验证的模板,Spring Boot 官方推荐使用 thymeleaf 而不是 JSP。

4、Thymeleaf 官网:https://www.thymeleaf.org/

5、Thymeleaf 在 Github 的主页:https://github.com/thymeleaf/thymeleaf

6、Spring Boot 中使用 Thymeleaf 模板引擎时非常简单,因为 Spring Boot 已经提供了默认的配置,比如解析的文件前缀,文件后缀,文件编码,缓存等等,程序员需要的只是写 html 中的内容即可,可以参考《Spring Boot 引入 Thymeleaf 及入门》

模板引擎

1)市面上主流的 Java 模板引擎有:JSP、Velocity、Freemarker、Thymeleaf

2)JSP本质也是模板引擎,Spring Boot 官方推荐使用 “Thymeleaf”模板引擎

3)模板引擎原理图如下,模板引擎的作用都是将模板(页面)和数据进行整合然后输出显示,区别在于不同的模板使用不同的语法,如 JSP 的 JSTL 表达式,以及 JSP 自己的表达式和语法,同理 Thymeleaf 也有自己的语法

实例

pox.xml
引入thymeleaf的依赖

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

application.properties
在spring-boot中配置thymeleaf

spring.thymeleaf.servlet.content-type=text/html
#配合nekohtml使用,避免语法严格
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
spring.mvc.static-path-pattern=/static/**

Controller
在controller中跳转页面

@Controller
public class testController {

    @RequestMapping("index.html")
    public String test(Model model){

        model.addAttribute("data", "你好");

        return "index";
    }

}

需要注意的是,要在resources里面新建static和templates文件夹,前者装css文件等,后者装html

在这里插入图片描述
helloworld.html
需要注意的是必须要在命名空间引入 xmlns:th=“http://www.thymeleaf.org”

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
</head>
<body>

<h1 th:text="${data}">你好,世界!</h1>

</body>
</html>

其他

格式化日期:
<span th:text="${#dates.format(dir.updateTime, 'yyyy-MM-dd HH:mm:ss')}"></span>
获取相对路径:
<script th:src="@{{path}/static/jquery-1.10.2.min.js (path=${contextPath})}" type="text/javascript"></script>
script中获取相对路径:
<script type="text/javascript" th:inline="javascript">
var basePath = ${#httpServletRequest.getContextPath()};

------基础操作------

  • 循环
<option th:each="s:${suppliers}" th:value="${s.id}" th:text="${s.name}"></option>

相当于在jsp中

<option th:each="s:${supplierList}" ></option>
<c:forEach items="${suppliers}" var="s">
<option value="${s.id}">${s.name}</option>
</c:forEach>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

丁racy

感谢各位兄弟的打赏!O(∩_∩

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

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

打赏作者

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

抵扣说明:

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

余额充值