Thymeleaf

Time:2021-10-20

Spring integrates thymeleaf template engine, which is introduced in this article

dialect

Thymeleaf provides a flexible interface that allows users to customize their own dialects. Therefore, it is necessary to understand the standard dialect before customizing the dialect.

Standard expression

${...}: variable expression

Variable

Variable expressions are usually ognl

${session.user.name}

Thymeleaf

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

Equivalent to springel or ognl

((Book)context.getVariable("book")).getAuthor().getName()

Read iteration from context

<li th:each="book : ${books}">

Select expression

Similar to the following, the current context is usually selected in the sub area, similar to that in the go template.

*{customer.name}

Complete example

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

Equivalent to

{
  // th:object="${book}"
  final Book selection = (Book) context.getVariable("book");
  // th:text="*{title}"
  output(selection.getTitle());
}

internationalization

It usually relies on key positioning to read local data.propertiesMessages in the corresponding language in the file

#{main.title}
#{message.entrycreated(${entryId})}

This is the case in the template

<table>
  ...
  <th th:text="#{header.address.city}">...</th>
  <th th:text="#{header.address.country}">...</th>
  ...
</table>

Of course, keys can also use variables

#{${config.adminWelcomeKey}(${session.user.name})}

link expression

Generate the root path based on the webserver context, assuming the root path / myapp

<a th:href="@{/order/list}">...</a>

corresponding

<a href="/myapp/order/list">...</a>

Hold session

<a href="/myapp/order/list;jsessionid=23fa31abd41ea093">...</a>

URL with parameters

<a th:href="@{/order/details(id=${orderId},type=${orderType})}">...</a>

This may be the result

<a href="/myapp/order/details?id=23&amp;type=online">...</a>

Relative to the link of the server, the application context prefix is not added

<a th:href="@{~/contents/main}">...</a>

Protocol based absolute path

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

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

Fragment Expression

Sometimes the Department adds or replaces a piece of Java codeth:insertorth:replace

<div th:insert="~{commons :: main}">...</div>

or

<div th:with="frag=~{footer :: #main/text()}">
  <p th:insert="${frag}">
</div>

This work adoptsCC agreement, reprint must indicate the author and the link to this article