Thymeleaf(Java模板引擎)

时间:2023-03-09 21:26:29
Thymeleaf(Java模板引擎)

一、概念

1、Thymeleaf是Web和独立环境的开源的Java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至纯文本;
2、Thymeleaf可以在Web(基于Servlet)和非Web环境中工作,它更适合在基于MVC的Web应用程序的视图层提供XHTML / HTML5 ,但它甚至可以在脱机环境中处理任何XML文件。它提供完整的Spring Framework集成
3、在Web应用程序中,Thymeleaf旨在成为JSP的完全替代品,并实现自然模板的概念:模板文件,可以直接在浏览器中打开,仍然可以正确显示为网页;

二、环境配置

1、如果用maven需要下载thymeleaf-2.1.4.RELEASE.jar(http://www.thymeleaf.org/download.html ),然后在pom里添加依赖
2、整合spring的需要下载thymeleaf-spring4-2.1.4.RELEASE.jar(http://www.thymeleaf.org/download.html ),然后添加依赖
3、servlet配置

<!-- Scans the classpath of this application for @Components to deploy as beans -->
<context:component-scan base-package="com.test.thymeleaf.controller" /> <!-- Configures the @Controller programming model -->
<mvc:annotation-driven /> <!--Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<!--springMVC+jsp的跳转页面配置-->
<!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!--<property name="prefix" value="/WEB-INF/views/" />-->
<!--<property name="suffix" value=".jsp" />-->
<!--</bean>--> <!--springMVC+thymeleaf的跳转页面配置-->
<bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
</bean> <bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean> <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>

4、html
引用命名空间: <html xmlns:th="http://www.thymeleaf.org">
可避免编辑器出现html验证错误,但是不加对Thymeleaf的功能也没有影响;

三、语法

1、表达式

    ${name}        可用值表达式,变量取值(变量名name又后台传入);
*{name} 所有可用值表达式,从可用值中查找name,如果有上下文,比如上层(即父标签)是object,则查object中的name属性(th:object="")。
#{nmae} 消息表达式,国际化时使用,也可以使用内置的对象,比如date格式化数据;(消息通常指:外部文本抽取模板代码片段到模板文件外面, 使外部文本可以存在另一个文件中)
@{name} 链接表达式,用来配合link,src,href使用的
~{name} 片段表达式,用来引入公共部分代码片段,并进行传值操作使用;

示例:
    服务器变量 map.put("msgutext","<b>1111</b>");
    html内容:

    <div th:utext="${msgutext}"></div>        显示结果为粗体的1111
<div th:text="${msgutext}"></div> 显示结果为:<b>1111</b>

2、运算符

数学:+,-,*,/,%
    比较:gt,lt,ge,le,eq,ne
    逻辑:and,or,not,!
    条件:? :  ,?: (默认值,例:    value ?: defaultvalue,条件语句也可以不只要?号,相当于没有else)
    其他:+(字符串连接),_(禁止转义),||(替换,内容可包含非参数内容,如:<a href="" th:href="@{|xx${value}|}"

3、支持的html5操作

(基本所有属性都支持了,只是在前边加了一个th:)
常用th标签

th:id          替换id
th:text 替换标签内文本
th:utext html文本替换,可使文本内的标签生效
th:object 替换对象
th:value 属性赋值
th:with 变量赋值运算,例<div th:with="isEven=${prodStat.count}%2==0"></div>
th:style 替换样式
th:onclick 点击事件
th:each 属性赋值
th:if 条件判断,例:<a th:if="${userId == collect.userId}" >
th:unless 条件判断
th:href 链接地址
th:switch switch选择,和th:case一起使用
th:fragmetn 布局标签
th:include
th:replace
th:selected
th:src
th:inline
th:action
th:remove
th:attr 设置任意标签属性,一般较少用到,因为所有的属性都有对应的th:

一个标签内多个th属性生效的优先顺序:
include,each,if/unless/switch/case,with,attr/attrprepend/attrappend,value/href,src ,etc,text/utext,fragment,remove

4、内嵌数据类型

(内置于Contex中,可通过#直接访问)

dates            java.util.Date的功能方法,${#dates.createNow()}
calendars java.util.Calendar
numbers 数字
strings 字符串
objects objects功能类
bools 布尔值
arrays 数组功能类
lists list功能类
sets 集合功能类
maps 字典功能类 内置基本对象(可通过#访问)
ctx,vars,locale,request,response,session,servletContext

5、遍历

<tr th:each="data:${getdata}">
<td th:text="${data.id}"></td>
<td th:text="${data.name}"></td>
...
</tr>

大部分java集合类型都可以用此来遍历

同时th:each还提供了一个变量可以保存迭代状态
状态包含以下属性:

    index      索引,从0开始
count 计数,从1开始
size   集合内元素总数
current 当前迭代对象
even/odd 奇偶数个,bool类型
first 是否是第一个,bool类型
last 是否是最后一个,bool类型

示例:

 <li th:each="emp, status: ${employees}" th:class="${status.odd} ? 'odd': 'even'">
<span class="list" th:text="${emp.name}"></span>
<span class="list" th:text="${emp.gender == 1} ? '男': '女'"></span>
<span class="list" th:text="${{emp.birthday}}"></span>
<span class="list status" th:text="|index: ${status.index}; count: ${status.count}; size: ${status.size}; first: ${status.first}|"></span> </li>
</li>
<!--如果没有指定第二个参数的名字,有默认的以参数名+Stat为名字,如上没有指定status则可以使用empStat提取上边参数-->

6、条件(if,switch)

示例:

1)if
<tr th:each="test:${test}">
<td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td>
<td th:if="${test.Score} ge 60 and ${test.Score} le 70">中</td>
...
</tr>

2)if unless

<tr th:each="test:${test}">
<td th:if="${test.Score} gt 0 and ${test.Score} lt 60">不及格</td>
<td th:unless="${test.Score} gt 0 and ${test.Score} lt 60">及格</td>
</tr>

3)switch

    <tr th:each="test:${test}">
<td th:switch="${test.male}">
<span th:case="1">男</span>
<span th:case="2">女</span>
<span th:case="*">未知</span>
</td>
</tr>

7、其他

1)外围包裹th:block标签:主要用于在代码外部加一层条件,而不用多写一个div

2)日期格式化:

<td th:text="${#dates.format(content.createDate,'yyyy-MM-dd HH:mm:ss')}"></td>

3)字符串长度截取:

<td th:if="${#strings.length(content.title) gt 5 } "  th:text="${#strings.substring(content.title,0,5) + '…'}"></td>

4)下拉选择:

 <select name="subId" id="subId" lay-verify="" >
<option value="">请选择</option>
<option th:each="channelsub:${subchannels}" th:selected="${channelsub.id == subId}" th:value="${channelsub.id}" th:text="${channelsub.name}"></option>
</select>

5)传值到js

 <script th:inline="javascript">
var size= [[${test.size()}]];
</script>

6)传值到css

<style th:inline="css">
.[[${classname}]] {
text-align: [[${align}]];
}
</style>