Thymeleaf syntax summary
I. Introduction to Thymeleaf
Thymeleaf is the recommended template engine for Spring Boot. It is displayed directly in HTML and can be separated from the front and back ends.
2, Thymeleaf3
XMLNS :th=”http://www.thymeleaf.org” XMLNS :th=”http://www.thymeleaf.org”
1) th:text;2Th: UText: supports HTML text replacement.3Th :value: attribute assignment4) th:each: iterate over the loop element5Th:if: judgment conditions, like th:unless, th:switchTh:case
6) th:insert: code block introduction, similar to th:replace, th:include, commonly used in common code block extraction scenarios7Th :fragment: defines a block of code that can be referenced by th:insert8Th :object: declare a variable, usually with *{} together, to achieve lazy effect.9Th :attr: Sets label attributes. Multiple attributes can be separated by commasCopy the code
Example:
<! DOCTYPE html><! -- namespace -->< HTML lang="en" xmlns:th="http://www.thymeleaf.org"><head>
<meta charset="UTF-8">< title>Thymeleaf syntax </title></head><body> <h2>ITDragon Thymeleaf syntax </h2> <! --th:text Sets the text content of the current element --> <p th:text="${thText}" />
<p th:utext="${thUText}"/ > <! --th:value Sets the value of the current element. The priority is higher than th:text --> <input type="text" th:value="${thValue}"/ > <! --th:each traversal list, common, high priority, only after code block insertion --> <! <div th:each= --> <div th:each="message : ${thEach}"> <! --> <p th:text="${message}"/> </div> <div> <! --> <p th:text="${message}" th:each="message : ${thEach}"/> </div> <! --th:ifConditional judgment, similar to th:switchTh:case, the priority is next to th:each, whereStrings is a built-in method for variable expressions -->
<p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p> <! --th:insert into the current div, with the highest priority, like th:replace, th:include, ~{} : block expression --> <div th:insert="~{grammar/common::thCommon}"></div> <! --th:object declares a variable with *{} --> <div th:object="${thObject}">
<p>ID: <span th:text="*{id}"/></p><! --th:text="${thObject.id}"-->
<p>TH: <span th:text="*{thName}"/></p><! --${thObject.thName}--> <p>DE: <span th:text="*{desc}"/></p><! --${thObject.desc}--> </div></body></html>Copy the code
Background the controller:
import com.itdragon.entities.ThObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Controller
public class ThymeleafController {
@RequestMapping("thymeleaf")
public String thymeleaf(ModelMap map) {
map.put("thText"."Th :text Sets the text content bold ");
map.put("thUText"."Th: UText set text content bold ");
map.put("thValue"."ThValue Sets the value of the current element");
map.put("thEach", Arrays.asList("th:each"."Walk through the list"));
map.put("thIf"."msg is not null");
map.put("thObject".new ThObject(1L."th:object"."Th attribute for laziness"));
return "grammar/thymeleaf"; }}Copy the code
2, standard expression syntax:
The ${… } Variable Expressions, Variable Expressions
@ {… } Link expression, Link URL Expressions
# {… } Message Expressions, Message Expressions
~ {… } Block expression, Fragment Expressions
* {… } Select Variable Expressions, Selection Variable Expressions
~ {… } code block expression
Supports two grammatical structure recommendation: ~ {templatename: : fragmentname}
Support: ~ {templatename: : # id}
Templatename: template name, Thymeleaf will according to the full path to the template name resolution: / resources/templates/templatename. HTML, attention should be paid to the path of the file.
Th :fragment=” fragmentName”
Id: HTML ID selector, preceded by a #, does not support the class selector.
Use of block expressions Block expressions need to be used with th attributes (th: INSERT, th:replace, th:include).
Th :insert: Inserts the entire code block fragment into the HTML tag that uses th:insert,
Th :replace: replaces the entire code block fragment using the TH :replace HTML tag,
Th :include: Inserts the contents of the code block fragment into the HTML tag that uses th:include.
{… } message expression
Message expressions are typically used in internationalization scenarios.
@ {… } link expression
Link expression benefits From static resource references, form requests, any link can use @{… }. This allows the project path to be retrieved dynamically and accessed normally even if the project name is changed
Server. context-path=/itdragon link expression structure no parameter: @{/ XXX}
@{/ XXX (k1=v1,k2=v2)} @{/ XXX (k1=v1,k2=v2)} k1=v1&k2=v2
Import local resources: @{/ project local resource path}
Import external resources: @{/webjars/ the path of resources in jars}
List:
<link th:href="@ {/ webjars/bootstrap / 4.0.0 / CSS/bootstrap CSS}" rel="stylesheet">
<link th:href="@{/main/css/itdragon.css}" rel="stylesheet">
<form class="form-login" th:action="@{/user/login}" th:method="post" >
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}"> 英 文</a> <a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
Copy the code
The ${… } variable expression
Variable expression function 1, you can get object properties and methods
You can use CTX, Vars, locale, Request, Response, session, servletContext built-in objects
We can use dates, numbers, strings, Objects, Arrays, Lists, sets, maps and other built-in methods.
CTX: context object.
Vars: context variables.
A: I’m not going to be locale.
Request :(web context only) HttpServletRequest object.
HttpServletResponse object for Response (only in web context).
Session :(in web context only) the HttpSession object.
ServletContext: a servletContext object (only in web context)
This section uses a common Session as an example. After a user posts successfully, the user information is stored in the Session. Thymeleaf obtains the value from the Session through the built-in object.
// The Java code places the user name in session
session.setAttribute("userinfo",username);
// Thymeleaf is obtained directly from the built-in object
th:text="${session.userinfo}"
Copy the code
Common built-in method 1, strings: string formatting method, it has common Java methods. Such as: Equals, equalsIgnoreCase, Length, trim, toUpperCase, toLowerCase, indexOf, SubString, replace, startsWith, endsWith, contains, ContainsIgnoreCase etc.
Numbers: numbers formatting methods, such as formatDecimal, etc
Bools: Boolean methods, such as isTrue, isFalse, etc
Array methods: toArray, Length, isEmpty, Contains, containsAll, etc
5, Lists, sets: set method, commonly used methods are: toList, size, isEmpty, contains, containsAll, sort, etc
Maps object methods include: size, isEmpty, containsKey, containsValue, and so on
Dates: format, Year, Month, Hour, and createNow are commonly used
<! DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head>
<meta charset="UTF-8">< title>ITDragon Thymeleaf built-in method </title></head><body> <h2>#strings </h3>
<div th:if="${not #strings.isEmpty(itdragonStr)}" >
<p>Old Str : <span th:text="${itdragonStr}"/></p>
<p>toUpperCase : <span th:text="${#strings.toUpperCase(itdragonStr)}"/></p>
<p>toLowerCase : <span th:text="${#strings.toLowerCase(itdragonStr)}"/></p>
<p>equals : <span th:text="${#strings.equals(itdragonStr, 'itdragonblog')}"/></p>
<p>equalsIgnoreCase :
<span th:text="${#strings.equalsIgnoreCase(itdragonStr, 'itdragonblog')}"/></p>
<p>indexOf : <span th:text="${#strings.indexOf(itdragonStr, 'r')}"/></p>
<p>substring : <span th:text="${#strings.substring(itdragonStr, 2, 8)}"/></p>
<p>replace : <span th:text="${#strings.replace(itdragonStr, 'it', 'IT')}"/></p>
<p>startsWith : <span th:text="${#strings.startsWith(itdragonStr, 'it')}"/></p>
<p>contains : <span th:text="${#strings.contains(itdragonStr, 'IT')}"/></p>
</div>
<h3>#numbers </h3><div> <p>formatDecimal Integer parts optional, with two decimal points reserved, rounded: <span th:text="${#numbers.formatDecimal(itdragonNum, 0, 2)}"/></p> <p>formatDecimal Integer parts keep five digits, two digits after the decimal point, rounded: <span th:text="${#numbers.formatDecimal(itdragonNum, 5, 2)}"/></p>
</div>
<h3>#bools </h3>
<div th:if="${#bools.isTrue(itdragonBool)}">
<p th:text="${itdragonBool}"></p>
</div>
<h3>#arrays </h3>
<div th:if="${not #arrays.isEmpty(itdragonArray)}">
<p>length : <span th:text="${#arrays.length(itdragonArray)}"/></p>
<p>contains : <span th:text="${#arrays.contains(itdragonArray, 5)}"/></p>
<p>containsAll : <span th:text="${#arrays.containsAll(itdragonArray, itdragonArray)}"/></p>
</div>
<h3>#lists </h3>
<div th:if="${not #lists.isEmpty(itdragonList)}">
<p>size : <span th:text="${#lists.size(itdragonList)}"/></p>
<p>contains : <span th:text="${#lists.contains(itdragonList, 0)}"/></p>
<p>sort : <span th:text="${#lists.sort(itdragonList)}"/></p>
</div>
<h3>#maps </h3>
<div th:if="${not #maps.isEmpty(itdragonMap)}">
<p>size : <span th:text="${#maps.size(itdragonMap)}"/></p>
<p>containsKey : <span th:text="${#maps.containsKey(itdragonMap, 'thName')}"/></p>
<p>containsValue : <span th:text="${#maps.containsValue(itdragonMap, '#maps')}"/></p>
</div>
<h3>#dates </h3>
<div>
<p>format : <span th:text="${#dates.format(itdragonDate)}"/></p>
<p>custom format : <span th:text="${#dates.format(itdragonDate, 'yyyy-MM-dd HH:mm:ss')}"/></p>
<p>day : <span th:text="${#dates.day(itdragonDate)}"/></p>
<p>month : <span th:text="${#dates.month(itdragonDate)}"/></p>
<p>monthName : <span th:text="${#dates.monthName(itdragonDate)}"/></p>
<p>year : <span th:text="${#dates.year(itdragonDate)}"/></p>
<p>dayOfWeekName : <span th:text="${#dates.dayOfWeekName(itdragonDate)}"/></p>
<p>hour : <span th:text="${#dates.hour(itdragonDate)}"/></p>
<p>minute : <span th:text="${#dates.minute(itdragonDate)}"/></p>
<p>second : <span th:text="${#dates.second(itdragonDate)}"/></p>
<p>createNow : <span th:text="${#dates.createNow()}"/></p>
</div></body></html>
Copy the code
@RequestMapping("varexpressions")public String varexpressions(ModelMap map) {
map.put("itdragonStr"."itdragonBlog");
map.put("itdragonBool".true);
map.put("itdragonArray".new Integer[]{1.2.3.4});
map.put("itdragonList", Arrays.asList(1.3.2.4.0));
Map itdragonMap = new HashMap();
itdragonMap.put("thName"."${#... }");
itdragonMap.put("desc"."Variable expression built-in methods");
map.put("itdragonMap", itdragonMap);
map.put("itdragonDate".new Date());
map.put("itdragonNum".888.888D); return "grammar/varexpressions";
}
Copy the code