模板引擎 Thymeleaf

如何识别Thymeleaf标准方言

<span th:text="...">
#需引入命名空间
<span data-th-text="...">
#不需要引入命名空间

变量表达式

语法: ${…}

<span th:text="${book.name}">

消息表达式

也称为文本外部化、国际化或i18n
语法:#{…}

选择表达式

语法:*{…}

<div th:object="${book}">
	...
	<span th:text="*{title}">...</span>
	...
</div>

与变量表达式区别:它们是在当前选择的对象而不是整个上下文变量映射上执行

链接表达式

语法:@{…}
链接表达式可以是相对的,在这种情况下,应用程序上下文将不会作为URL的前缀

<a th:href="@{../documents/report}">...</a>

也可以是服务器相对(同样,没有应用程序上下文前缀):

<a th:href="@{~/documents/report}">...</a>

和协议相对(就像绝对URL,但浏览器将使用在显示的页面中使用的相同的HTTP或HTTPS协议)

<a th:href="@{//static.mycompany.com/res/initial}">...</a>

当然,Link表达式可以是绝对的:

<a th:href="@{http://www.mycompany.com/res/initial}">...</a>

分段表达式

语法:th:insert 或 th:replace

字面量(文字)

文本

<span th:text="'working web application'"></span>

数字

<span th:text="2019+1"></span>

布尔

<div th:if="${user.isAdmin()} == false"></div>

null

<div th:if="${variable.something} == null"></div>

算术操作

如 + - * / %

<div th:with="isEven(${prodStat.count}	% 2	==	0)">

比较和等价

、 <、 >=、 <=、 (gt、 lt、 ge、 le)
==、 !=、 (eq、 ne)

条件运算符

<tr th:class="${row.even} ? 'even' : 'odd'">
	...
</tr>

无操作

_ (下划线)

	<span th:text="${user.name] ?  :  _">no user authenticated</span>
	#用户不存在,什么都不做

设置属性值

设置任意属性值 th:attr

<form action="subscribe.html" th:attr="action=@{/subscribe}">
	<fieldset>
			<input type="text" name="email"/>
			<input type="submit" value="Subscrbe!" th:attr="value=#{subscribe.submit}"/>
		</fieldset>
</form>

设置值到指定的属性

<form action="subscribe.html" th:action="@{/subscribe}">
	<fieldset>
			<input type="text" name="email"/>
			<input type="submit" value="Subscrbe!" th:value="#{subscribe.submit}"/>
		</fieldset>
</form>

固定值布尔属性

<input type="checkbox" name="option2" checked/>
thymeleaf表示为
<input type="checkbox" name="option2" th:checked="${user.active}"/>
#如果user.active为false,checked就不显示了

迭代

基本的迭代 th:each

<li th:each="book : ${books}" th:text="${book.title}"> en las Orillas del Sar</li>

数组、List、Map

状态变量

  • index、 count、 size、 current、 even/odd、 first 、last

条件语句

th:if 、th:unless

<span th:if="${not #lists.isEmpty(prod.comments)}">view</span>

<span th:unless="${lists.isEmpty(prod.comments)}">view</span>

switch

<div th:switch=${user.role}>
	<p th:case="'admin'"> User is an administrator</p>
	<p th:case="#{roles.manager}"> User is a manager</p>
	<p th:case="*"> User is some other thing</p>
</div>

模板布局

定义片段

footer.html

<html xmlns:th="http://www.thymeleaf.org">
	<body>
		<div th:fragment="copy">
			&copy; 2019 <a href='http://www.giteasy.cn'> giteasy.cn</a>
		</div>
	</body>
</html>

不使用th:fragment

<html xmlns:th="http://www.thymeleaf.org">
	<body>
		<div id="copy-section">
			&copy; 2019 <a href='http://www.giteasy.cn'> giteasy.cn</a>
		</div>
	</body>
</html>

引用片段

<html xmlns:th="http://www.thymeleaf.org">
	<body>
		...
		<div th:insert="~{footer :: copy}">
		</div>
	</body>
</html>

引用未使用th:fragment定义的片段

<html xmlns:th="http://www.thymeleaf.org">
	<body>
		...
		<div th:insert="~{footer :: #copy-section}">
		</div>
	</body>
</html>

th:insert、 th:replace 、th:include三者区别

  • th:insert它将简单地插入指定的片段作为正文的主标签。
  • th:replace用指定实际片段来替换其主标签。
  • th:include类似于th:insert,但不是插入片段它只插入此片段的内容。(3.x版本后,不再推荐使用)

属性优先级

<ul>
<li th:each="item : ${items}" th:text="${item.description}">Item description here ... </li>
</ul>

th:each 与 th:text书写顺序不影响代码的执行

优先级

Order Feature Attributes
1 Fragment inclusion th:insert th:replace
2 Fragment iteration th:each
3 Conditional evaluation th:if th:unless th:switch th:case
4 Local variable definition th:object th:with
5 General attribute modification th:attr th:attrprepend th:attrappend
6 Specific attribute modification th:value th:href th:src …
7 Text(tag body modification) th:text th:utext
8 Fragment specification th:fragment
9 Fragment removal th:remove

注释

标准HTML/XML注释

<!-- User info follows -->
<div th:text="${...}"> 
	...
</div>

Thymeleaf 解析器级注释块

删除 之间的所有内容

<!--/* -->
<div th:text="${...}"> 
	...
</div>
<!-- */-->

原型注释块

当模板静态打开时(比如原型设计),原型注释 块所注释的代码将被注释,不显示。而在模版执行时,这些注释的代码,就能被显示出来。与解析器级注释块意义相反。

<span>hello!</span>
	<!--/*/
		<div th:text="${...}"> 
		...
		</div>
	/*/-->
<span>goodbye!</span>

内联

内联表达式

[[…]] 或 [(…)] 分别对应于th:text和th:utext

<p>The message is "[(${msg})]"</p>
执行后显示为
<p>The message is "This is <b>great!</b>"</p>
<p>The message is "[[${msg}]]"</p>
执行后显示为
<p>The message is "This is &lt;b&gt;great!&lt;/b&gt;"</p>

禁用内联 th:inline

有时需要禁用这种机制,比如,想输出[[…]]或[(…)]文本内容

<p th:inline="none"> A double array looks like this: [[1,2,3],[4,5]]!</p>

JavaScript内联

<script th:inline="javascript">
	...
	var username = /*[[${session.user.name}]]*/ "gertrud Kiwifruit";
	...
</script>

执行后

<script th:inline="javascript">
	...
	var username = "Sebastian \"Fruity\" Applejuice";
	...
</script>

CSS内联

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

执行后

<style th:inline="css">
	.main elems{
		text-align:center;
	}
</style>

表达式基本对象

基本对象

  • #ctx:上下文对象。是org.thymeleaf.context.IContext或者org.thymeleaf.context.IWebContext的实现
  • #locale: 直接访问与java.util.Locale关联的当前的请求
/*
*===========================================
* See javadoc API for class org.thymeleaf.context.IContext
*===========================================
*/
${#ctx.locale}
${#ctx.variableNames}


/*
*===========================================
* See javadoc API for class org.thymeleaf.context.IWebContext
*===========================================
*/

${#ctx.request}
${#ctx.response}
${#ctx.session}
${#ctx.servletContext}

${#locale}

request/session等属性

  • param:用于检索请求参数
  • session:用于检索session属性
  • application:用于检索application/servlet上下文属性
/*
*===========================================
* See javadoc API for class org.thymeleaf.context.WebRequestParamsVariablesMap
*===========================================
*/
${param.foo}
${param.size()}
${param.isEmpty()}
${param.containsKey('foo')}

/*
*===========================================
* See javadoc API for class org.thymeleaf.context.WebSessionVariablesMap
*===========================================
*/
${session.foo}
${session.size()}
${session.isEmpty()}
${session.containsKey('foo')}

/*
*===========================================
 * See javadoc API for class org.thymeleaf.context.WebServletContextVariablesMap
*===========================================
*/
${application.foo}
${application.size()}
${application.isEmpty()}
${application.containsKey('foo')}

Web上下文对象

  • #request: 直接访问与当前请求关联的javax.servlet.http.HttpServletRequest对象
  • #session: 直接访问与当前请求关联的javax.servlet.http.HttpSession对象
  • #servletContext: 直接访问与当前请求关联的javax.servlet.ServletContext对象
${#request.getAttribute('foo')}
${#request.getParameter('foo')}
${#request.getContextPath()}
${#request.getRequestName()}
...

${#session.getAttribute('foo')}
${#session.id}
${#session.lastAccessedTime}

...
${#servletContext.getAttribute('foo')}
${#servletContext.contextPath()}

thymeleaf Maven依赖


<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.3.RELEASE</version>
</dependency>

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>2.2.0</version>
</dependency>

github地址:https://github.com/gitAxin/thymeleaf-in-action.git

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章