Thymeleaf - 语法使用详解

可以从官网下载PDF进行参考:

https://www.thymeleaf.org/documentation.html

这里写图片描述

或者在线参考文档:

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

这里写图片描述


一个好的习惯是,每一个HTML页面引入Thymeleaf的名称空间:

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

【1】th:text和th:utext

th:text 将div里面的文本内容设置为动态取的值,如果有标签则进行转义,不让标签生效。

示例如下:

<div th:text="${hello}"></div>

th:utext 非转义文本,将div里面的文本内容原样输出设置为动态取的值。

<div th:utext="${hello}"></div>

后台代码如下:

@RequestMapping("/success")
public String success(Map<String,Object> map){
     map.put("hello","<h1>你好</h1>");
     map.put("users",Arrays.asList("zhangsan","lisi","wangwu"));
     return "success";
 }

结果如下:

这里写图片描述

查看网页源代码如下:

<div>&lt;h1&gt;你好&lt;/h1&gt;</div>
<div><h1>你好</h1></div>

【2】th标签的任意属性

th:任意html属性,来替换原生属性的值。

示例如下:

<div id="div01" class="myDiv" th:id="${hello}" 
th:class="${hello}" th:text="${hello}">这是显示欢迎信息</div>

【3】th属性优先级

属性优先级

既然可以写多个任意属性,那么肯定牵涉到属性生效的优先级问题。HTML并没有这种设置,幸运的是Thymeleaf有属性优先级设定。

这里写图片描述


【4】标准表达式语法

Thymeleaf提供了一系列语法、内置对象和工具方法来帮助我们开发。

① Simple expressions(五种基本表达式):

    Variable Expressions: ${...}
    Selection Variable Expressions: *{...}
    Message Expressions: #{...}
    Link URL Expressions: @{...}
    Fragment Expressions: ~{...}

② Literals(字面量)

    Text literals: 'one text' , 'Another one!' ,…
    Number literals: 0 , 34 , 3.0 , 12.3 ,…
    Boolean literals: true , false
    Null literal: null
    Literal tokens: one , sometext , main ,…

③ Text operations(文本操作):

    String concatenation: +
    Literal substitutions: |The name is ${name}|

④ Arithmetic operations(数学运算):

    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -

⑤ Boolean operations(布尔操作):

    Binary operators: and , or
    Boolean negation (unary operator): ! , not

⑥ Comparisons and equality(比较运算):

    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )

⑦ Conditional operators(条件运算):

    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)

⑧ Special tokens(特殊语法):

    No-Operation: _

【5】变量表达式 ${…}

We already mentioned that ${…} expressions are in fact OGNL (Object-Graph Navigation Language) expressions executed on the map of variables contained in the context.

① 其语法示例如下:

/*
* Access to properties using the point (.). Equivalent to calling property getters.
*/
${person.father.name}
/*
* Access to properties can also be made by using brackets ([]) and writing
* the name of the property as a variable or between single quotes.
*/
${person['father']['name']}
/*
* If the object is a map, both dot and bracket syntax will be equivalent to
* executing a call on its get(...) method.
*/
${countriesByCode.ES}
${personsByName['Stephen Zucchini'].age}
/*
* Indexed access to arrays or collections is also performed with brackets,
* writing the index without quotes.
*/
${personsArray[0].name}
/*
* Methods can be called, even with arguments.
*/
${person.createCompleteName()}
${person.createCompleteNameWithSeparator('-')}

② Expression Basic Objects

When evaluating OGNL expressions on the context variables, some objects are made available to expressions for higher flexibility. These objects will be referenced (per OGNL standard) starting with the # symbol:

#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.

示例如下:

${#locale.country}"
${#request.getAttribute('foo')}
${#request.getParameter('foo')}
${#request.getContextPath()}
${#request.getRequestName()}
//具体参考官方文档的附录A

③ Expression Utility Objects

Besides these basic objects, Thymeleaf will offer us a set of utility objects that will help us perform common tasks in our expressions.

这个很给力,提供了一系列工具类对象来帮助我们进行页面开发。

#execInfo : information about the template being processed.

#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they
would be obtained using #{…} syntax.

#uris : methods for escaping parts of URLs/URIs

#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.

#calendars : analogous to #dates , but for java.util.Calendar objects.

#numbers : methods for formatting numeric objects.

#strings : methods for String objects: contains, startsWith, prepending/appending, etc.

#objects : methods for objects in general.

#bools : methods for boolean evaluation.

#arrays : methods for arrays.

#lists : methods for lists.

#sets : methods for sets.

#maps : methods for maps.

#aggregates : methods for creating aggregates on arrays or collections.

#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

示例如下:

${#calendars.format(cal)}
${#calendars.arrayFormat(calArray)}
${#numbers.formatInteger(num,3)}
${#numbers.arrayFormatInteger(numArray,3)}
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#objects.nullSafe(obj,default)}
${#objects.arrayNullSafe(objArray,default)}
//...具体参考附录B

页面示例如下:

<p style="color: red" th:text="${msg}" 
th:if="${not #strings.isEmpty(msg)}">
</p>

【6】选择表达式*{…}

Not only can variable expressions be written as ${…} , but also as *{…} .

There is an important difference though: the asterisk syntax evaluates expressions on selected objects rather than on the whole context. That is, as long as there is no selected object, the dollar and the asterisk syntaxes do exactly the same.

And what is a selected object? The result of an expression using the th:object attribute. Let’s use one in our user profile ( userprofile.html ) page:

<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>

Which is exactly equivalent to:

<div>
<p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

Of course, dollar and asterisk syntax can be mixed:

<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>

*号表达是和$表达式在没有对象被选择的时候,是一样的。区别在于如果有对象被选择如<div th:object="${session.user}">,*号表达式可以直接使用th:text="*{firstName}获取属性值。二者也可以同时混淆使用。


通常用来为页面的请求设置URL,示例如下:

① 使用全路径


<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html"
th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>

② 相对于项目根目录


<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

③ 路径中使用资源标识


<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

th:href将会替换a标签中的href属性值。


④ 在form表单使用

<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit"/>
</form>

⑤ 在head link中引入CSS

<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">

⑥ URL多参数示例

@{/order/process(execId=${execId},execType='FAST')}

⑦ URL拼接

<a th:href="@{${url}(orderId=${o.id})}">view</a>
<a th:href="@{'/details/'+${user.login}(orderId=${o.id})}">view</a>

⑧ 自动拼接contextPath

Relative URLs starting with / (eg: /order/details ) will be 
automatically prefixed by the application context name.

这个是很友好的,Thymeleaf会自动将项目contextPath拼接在URL前面。

如项目contextPath分别为/ , /crud,则使用@{/asserts/css/signin.css}分别显示如下:

/asserts/css/signin.css;
/crud/asserts/css/signin.css;

⑨ 支持URL重写

If cookies are not enabled or this is not yet known, a “;jsessionid=…” suffix might be added to relative URLs so that the session is preserved.

This is called URL Rewriting and Thymeleaf allows you to plug in your own rewriting filters by using the response.encodeURL(…) mechanism from the Servlet API for every URL.


【8】Fragments~{…}

片段引用表达式,类似于<jsp:include page="inlayingJsp.jsp" flush="true"/>或者<%@ include file="inlayingJsp.jsp" %>或者<c:import url="inlayingJsp.jsp"/>…等等还有很多其他类似方式。

即,在当前页面引入其他页面或者片段 !


【9】遍历th:each

后台代码如下:

 @RequestMapping("/success")
 public String success(Map<String,Object> map){
     map.put("hello","<h1>你好</h1>");
     map.put("users",Arrays.asList("zhangsan","lisi","wangwu"));
     return "success";
 }

页面如下:

<!-- th:each每次遍历都会生成当前这个标签: 3个h4 -->
<h4 th:text="${user}"  th:each="user:${users}"></h4>
<hr/>
<h4>
    <span th:each="user:${users}"> [[${user}]] </span>
</h4>

显示如下:

这里写图片描述

其中[[${user}]]叫做行内写法,官方说明如下:

Expressions between [[…]] or [(…)] are considered inlined expressions in Thymeleaf, and inside them we can use any kind of expression that would also be valid in a th:text or th:utext attribute.

Note that, while [[…]] corresponds to th:text (i.e. result will be HTML-escaped), [(…)] corresponds to th:utext and will not perform any HTML-escaping.

猜你喜欢

转载自blog.csdn.net/j080624/article/details/80683328