thymeleaf模板

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_40298351/article/details/102733554

一、Thymeleaf 介绍

    Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。

     Thymeleaf是与众不同的,因为它使用了自然的模板技术。这意味着Thymeleaf的模板语法并不会破坏文档的结构,模板依旧是有效的XML文档。模板还可以用作工作原型,Thymeleaf会在运行期替换掉静态值。Velocity与FreeMarker则是连续的文本处理器。 下面的代码示例分别使用Velocity、FreeMarker与Thymeleaf打印出一条消息:

  • Velocity: <p>$message</p>
  • FreeMarker: <p>${message}</p>
  • Thymeleaf: <p th:text="${message}">Hello World!</p>

注意,由于Thymeleaf使用了XML DOM解析器,因此它并不适合于处理大规模的XML文件。

二、引用方式

(1)添加maven依赖

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

 (2)引入模版

<html xmlns:th="http://www.thymeleaf.org">

(3)文件配置

spring:
  thymeleaf:
    cache: false #关闭缓存
    prefix: classpath:/views/ #添加路径前缀

三、基础语法

(1)变量表达式${}

使用方法:直接使用th:xx = "${}" 获取对象属性 。例如:

<input id="username" name="username" th:value="${username}"/>
<div th:text="${user.username}"></div>

(2)选择变量表达式*{}

    使用方法:首先通过th:object 获取对象,然后使用th:xx = "*{}"获取对象属性。这种简写风格极为清爽,推荐大家在实际项目中使用。 例如:

<form id="userForm" th:object="${user}">
    <input id="id" name="id" th:value="*{id}"/>
    <input id="username" name="username" th:value="*{username}"/>
    <input id="password" name="password" th:value="*{password}"/>
</form>

(3)链接表达式@{}

    使用方法:通过链接表达式@{}直接拿到应用路径,然后拼接静态资源路径。例如:

<script th:src="@{/jquery/jquery.js}"></script>
<link th:href="@{/bootstrap/css/bootstrap.css}" rel="stylesheet" type="text/css">

(4)片段表达式 ~{}

片段表达式是Thymeleaf的特色之一,细粒度可以达到标签级别,这是JSP无法做到的。片段表达式拥有三种语法:

  • ~{ viewName } 表示引入完整页面
  • ~{ viewName ::selector} 表示在指定页面寻找片段 其中selector可为片段名、jquery选择器等
  • ~{ ::selector} 表示在当前页寻找

使用方法:首先通过th:fragment定制片段 ,然后通过th:replace 填写片段路径和片段名。例如:

<!-- /views/commons/head.html-->
<head th:fragment="static">
        <script th:src="@{/jquery/3.3.1/jquery.js}"></script>
</head>

<!-- /views/my.html -->
<div th:replace="~{commons/head::static}"></div>

在实际使用中,我们往往使用更简洁的表达,去掉表达式外壳直接填写片段名。例如:

<!-- my.html -->
<div th:replace="commons/head::static"></div>

    使用替换路径th:replace 开头请勿添加斜杠,避免部署运行的时候出现路径报错。(因为默认拼接的路径为spring.thymeleaf.prefix = classpath:/templates/

(5)消息表达式
即通常的国际化属性:#{msg} 用于获取国际化语言翻译值。例如:

 <title th:text="#{user.title}"></title>

(6)其他

在基础语法中,默认支持字符串连接、数学运算、布尔逻辑和三目运算等。例如:

<input name="name" th:value="${'我是: '+(user.name!=null?user.name:'游客')}"/>

四、内置对象

(1)基础对象

${#ctx} 上下文对象,可用于获取其它内置对象。
${#vars}: 上下文变量。
${#locale}:上下文区域设置。
${#request}: HttpServletRequest对象。
${#response}: HttpServletResponse对象。
${#session}: HttpSession对象。
${#servletContext}: ServletContext对象。

(2)常用的工具类:

#strings:字符串工具类
#lists:List 工具类
#arrays:数组工具类
#sets:Set 工具类
#maps:常用Map方法。
#objects:一般对象类,通常用来判断非空
#bools:常用的布尔方法。
#execInfo:获取页面模板的处理信息。
#messages:在变量表达式中获取外部消息的方法,与使用#{...}语法获取的方法相同。
#uris:转义部分URL / URI的方法。
#conversions:用于执行已配置的转换服务的方法。
#dates:时间操作和时间格式化等。
#calendars:用于更复杂时间的格式化。
#numbers:格式化数字对象的方法。
#aggregates:在数组或集合上创建聚合的方法。
#ids:处理可能重复的id属性的方法。

五、迭代循环

想要遍历List集合很简单,配合th:each 即可快速完成迭代。例如遍历用户列表:

<div th:each="user:${userList}">
    账号:<input th:value="${user.username}"/>
    密码:<input th:value="${user.password}"/>
</div>

    在集合的迭代过程还可以获取状态变量,只需在变量后面指定状态变量名即可,状态变量可用于获取集合的下标/序号、总数、是否为单数/偶数行、是否为第一个/最后一个。例如:

<div th:each="user,stat:${userList}" th:class="${stat.even}?'even':'odd'">
    下标:<input th:value="${stat.index}"/>
    序号:<input th:value="${stat.count}"/>
    账号:<input th:value="${user.username}"/>
    密码:<input th:value="${user.password}"/>
</div>

如果缺省状态变量名,则迭代器会默认帮我们生成以变量名开头的状态变量 xxStat, 例如:

<div th:each="user:${userList}" th:class="${userStat.even}?'even':'odd'">
    下标:<input th:value="${userStat.index}"/>
    序号:<input th:value="${userStat.count}"/>
    账号:<input th:value="${user.username}"/>
    密码:<input th:value="${user.password}"/>
</div>

六、条件判断

条件判断通常用于动态页面的初始化,例如:

<div th:if="${userList}">
    <div>用户列表</div>
</div>

如果想取反则使用unless 例如:

<div th:unless="${userList}">
    <div>无用户列表</div>
</div>

七、日期格式化

使用默认的日期格式(toString方法) 并不是我们预期的格式:Mon Dec 03 23:16:50 CST 2018

<input type="text" th:value="${user.createTime}"/>

此时可以通过时间工具类#dates来对日期进行格式化:2018-12-03 23:16:50

<input type="text" th:value="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm:ss')}"/>

八、内联写法

  1. 为什么要使用内联写法?·答:因为 JS无法获取服务端返回的变量。
  2. 如何使用内联表达式?答:标准格式为:[[${xx}]] ,可以读取服务端变量,也可以调用内置对象的方法。例如获取用户变量和应用路径:
  3. 标签引入的JS里面能使用内联表达式吗?答:不能!内联表达式仅在页面生效,因为Thymeleaf只负责解析一级视图,不能识别外部标签JS里面的表达式。
    <script th:inline="javascript">
        var user = [[${user}]];`
        var APP_PATH = [[${#request.getContextPath()}]];
        var LANG_COUNTRY = [[${#locale.getLanguage()+'_'+#locale.getCountry()}]];
    </script>

 

猜你喜欢

转载自blog.csdn.net/qq_40298351/article/details/102733554