Thymeleaf Tutorial (Getting Started in 10 Minutes)

Thymeleaf is a template engine for rendering XML/XHTML/HTML5 content. It is similar to template engines such as JSP, Velocity, FreeMaker, etc., and can also be easily integrated with Web frameworks such as Spring MVC. Compared with other template engines, the biggest feature of Thymeleaf is that even if the web application is not started, the template page can be opened directly in the browser and displayed correctly.

  1. Introduction to Thymeleaf
    Thymeleaf is a new generation of Java template engine. Unlike traditional Java template engines such as Velocity and FreeMarker, Thymeleaf supports HTML prototypes, and its file suffix is ​​".html", so it can be opened directly by the browser, and the browser will ignore it at this time. Undefined Thymeleaf tag attributes, showing the static page effect of the thymeleaf template; when accessed through a web application, Thymeleaf will dynamically replace the static content to make the page dynamically displayed.

Thymeleaf achieves the display mode of "template + data" by adding additional attributes in the html tag, the sample code is as follows.

Title

Welcome to the static page HTML

When opened directly with a browser, the browser displays the results as follows.

Welcome to the static page HTML

When accessed through the web application, the browser displays the results as follows.

Welcome to Thymeleaf
Thymeleaf features
Thymeleaf template engine has the following features:
Combination of dynamic and static: Thymeleaf can be opened directly with a browser to view the static effect of the page, or accessed through a web application to view the dynamic page effect.
Out of the box: Thymeleaf provides Spring standard dialect and an optional module that is perfectly integrated with SpringMVC, which can quickly implement functions such as form binding, property editor, and internationalization.
Multi-dialect support: It provides Thymeleaf standard and Spring standard two dialects, which can directly apply templates to implement JSTL and OGNL expressions; developers can also expand and create custom dialects when necessary.
Perfect integration with SpringBoot: SpringBoot provides a default configuration for Thymeleaf, and also sets a view resolver for Thymeleaf, so Thymeleaf can be perfectly integrated with Spring Boot.
2. Thymeleaf syntax rules
Before using Thymeleaf, first declare the namespace in the html tag of the page, the sample code is as follows.

xmlns:th="http://www.thymeleaf.org"
Declare this namespace in the html tag to avoid html validation errors in the editor, but this step is not necessary, even if we do not declare the namespace Does not affect the use of Thymeleaf.

As a template engine, Thymeleaf has its own grammar rules. Thymeleaf syntax is divided into the following 2 categories:

Standard expression syntax
th attribute
2.1 Standard expression syntax
Thymeleaf template engine supports a variety of expressions:

Variable expression: ${…}
Selection variable expression: *{…}
Link expression: @{…}
Internationalization expression: #{…}
Fragment reference expression: ~{…}
2.1.1 Variable expression
use The expression wrapped by ${} is called a variable expression, which has the following functions:

Get properties and methods of an object
Use built-in primitive objects
Use built-in utility objects

① Get the properties and methods of the object

The properties and methods of objects can be obtained by using variable expressions. For example, to obtain the lastName property of a person object, the expression form is as follows:

${person.lastName}

② Use built-in basic objects

Using variable expressions, you can also use built-in basic objects, get properties of built-in objects, and call methods of built-in objects. The built-in basic objects commonly used in Thymeleaf are as follows:

#ctx : context object;
#vars : context variable;
#locale: context locale;
#request: HttpServletRequest object (only available in web applications);
#response: HttpServletResponse object (only available in web applications);
#session : HttpSession object (only available in Web applications);
#servletContext: ServletContext object (only available in Web applications).

For example, we can obtain the map attribute in the session object through the following two forms:

${#session.getAttribute(‘map’)}
${session.map}

③ Use built-in tool objects

In addition to being able to use built-in basic objects, variable expressions can also use some built-in utility objects.

strings: String tool object, commonly used methods are: equals, equalsIgnoreCase, length, trim, toUpperCase, toLowerCase, indexOf, substring, replace, startsWith, endsWith, contains and containsIgnoreCase, etc.; numbers: Number tool object, commonly used methods are:
formatDecimal etc.;
bools: Boolean tool object, commonly used methods are: isTrue and isFalse, etc.;
arrays: array tool object, commonly used methods are: toArray, length, isEmpty, contains and containsAll, etc.;
lists/sets: List/Set collection tool object , commonly used methods are: toList, size, isEmpty, contains, containsAll and sort, etc.;
maps: Map collection tool object, commonly used methods are: size, isEmpty, containsKey and containsValue, etc.; dates
: date tool object, commonly used methods are : format, year, month, hour, createNow, etc.

For example, we can use the equals method of the built-in tool object strings to determine whether a string is equal to a property of an object, the code is as follows.

${#strings.equals('Programming Help',name)}
2.1.2 Select variable expression
Select variable expression is basically the same function as variable expression, except that the cooperation with th:object is added on the basis of variable expression use. After using th:object to store an object, we can use the selection variable expression ({…}) in its descendants to obtain the properties in the object, where " " represents the object.

firstname

th:object is used to store a temporary variable, which is only valid in the tag and its descendants, and I will introduce it in detail in the "th attribute" in the following content.

2.1.3 Link expression
Whether it is a static resource reference or a form form request, any link can use a link expression (@{…}).

The formal structure of the link expression is as follows:

Request without reference: @{/xxx}
Request with reference: @{/xxx(k1=v1,k2=v2)}

For example, use the link expression to import the css style sheet, the code is as follows.

2.1.4 Internationalized expressions Message expressions are generally used in internationalized scenarios. The structure is as follows.

th:text="#{msg}"
Note: Just understand here, we will introduce it in detail in the following chapters.

2.1.5 Fragment reference expression
Fragment reference expression is used to refer to other template fragments in the template page, and the expression supports the following 2 syntax structures:

Recommended: ~{templatename::fragmentname}
Supported: ~{templatename::#id}

The above grammatical structure is explained as follows:

templatename: template name, Thymeleaf will resolve the full path according to the template name: /resources/templates/templatename.html, pay attention to the path of the file.
fragmentname: Fragment name, Thymeleaf defines code blocks through th:fragment declaration, namely: th:fragment="fragmentname"
id: HTML id selector, when using it, add # in front, class selector is not supported.
2.2 th attribute
Thymeleaf also provides a large number of th attributes, which can be used directly in HTML tags, and the commonly used th attributes and their examples are shown in the following table.
insert image description here
insert image description here
3. Thymeleaf public page extraction
In web projects, there are usually some public page fragments (duplicate codes), such as the header navigation bar, side menu bar, and public js css. We generally extract these public page fragments and store them in an independent page, and then be referenced by other pages as needed, which can eliminate code duplication and make the page more concise.
3.1 Extracting public pages
Thymeleaf, as an elegant and highly maintainable template engine, also supports the extraction and reference of public pages. We can extract public page fragments and store them in an independent page, and use the th:fragment attribute provided by Thymeleaf to name these extracted public page fragments.
Example 1
extracts the common page fragment and stores it in commons.html, the code is as follows.

public page fragment
3.2 Citing public pages In Thymeleaf, we can use the following three attributes to introduce public page fragments into the current page. th:insert: Insert the entire code block fragment into the HTML tag using the th:insert attribute; th:replace: Replace the entire code block fragment into the HTML tag using the th:replace attribute; th:include: Insert the code block The included content of the fragment is inserted into HTML tags using the th:include attribute.

Using the above three attributes to introduce page fragments can be achieved in the following two ways.
~{templatename::selector}: template name::selector
~{templatename::fragmentname}: template name::fragment name
Normally, ~{} can be omitted, and its inline writing method is [[~{…}]] Or [(~{…})], where [[~{…}]] escapes special characters and [(~{…})] does not.

Example 2

  1. Introducing page fragments declared in commons.html into page fragment.html can be achieved in the following ways.
------------------------------------------------
------------------------------------------------
  1. Start Spring Boot, use a browser to access fragment.html, and view the source code. The results are as follows.
public page fragment
public page fragment
------------------------------------------------
public page fragment
public page fragment
------------------------------------------------
public page fragment
public page fragment
3.3 Passing parameters When Thymeleaf extracts and imports public page fragments, it can also pass parameters. The general steps are as follows: Pass in parameters; Use parameters. 3.3.1 Incoming parameters When referring to a public page fragment, we can pass parameters into the referenced page fragment in the following two ways: template name::selector name or fragment name (parameter 1=parameter value 1, Parameter 2=parameter value 2) template name:: selector name or fragment name (parameter value 1, parameter value 2) Note:

If there are few incoming parameters, the second method is generally used to directly pass the parameter value into the page fragment;
if there are many parameters, it is recommended to use the first method to clearly specify the parameter name and parameter value.
The sample code is as follows:

------------------------------------------------
------------------------------------------------
3.3.2 Using parameters When declaring a page fragment, we can declare and use these parameters in the fragment, for example:

...

Start Spring Boot, use a browser to access fragment.html, the result is as shown below.

Thymeleaf page parameter passing effect diagram
insert image description here

Guess you like

Origin blog.csdn.net/weixin_64842782/article/details/125089695