This is the 28th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Basic usage of Thymeleaf

Most of the content comes from the Internet

We’re not going to use SpringMVC as an integration here or with Spring Boot

We’ll use the servlet version alone here – just to provide some of the code for beginners

Thymeleaf is a template engine for rendering XML/XHTML/HTML5 content, similar to JSP, Velocity, FreeMaker, etc. It can also be easily integrated with Spring MVC and other Web frameworks as a template engine for Web applications.

Thymeleaf’s biggest feature is the ability to open and display template pages correctly in a browser without having to launch the entire Web application, but it’s always been said to be a bit inefficient

Thymeleaf works both on and off the web, meaning it allows artists to view static pages in the browser and programmers to view dynamic pages with data on the server. This is because it supports HTML prototypes and then adds additional attributes to HTML tags to achieve the template + data presentation. Browsers ignore undefined tag attributes when interpreting HTML, so Thymeleaf's template can run statically; When data is returned to the page, the Thymeleaf tag dynamically replaces the static content and makes the page display dynamically. Thymeleaf features out of the box. It provides standard and Spring standard two dialects, can directly apply template to achieve JSTL, OGNL expression effect, avoid every day set template, change JSTL, change label trouble. Developers can also extend and create custom dialects.Copy the code

1. Introduce hints

The thymeleaf namespace is introduced in HTML pages, that is, dynamic attributes in HTML template files are decorated with th: namespace.

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

This allows the syntax th:* to be used in other tags. This is the premise of the following syntax.

2. Variable expression (get variable value)

<div th:text=+${session.book}+'!! '">Somewhat similar to the EL expression, if there is data, it is replaced to complete the front end separation effect (art code)</div>
Copy the code
1. It can be seen that the value of the variable with the $symbol, for javaBean words to use the variable name. 2. It uses the th:text attribute in the tag to fill in a section of the tag. The $expression can only be written inside the th tag, otherwise it will not work. In this example, the value of the th:text tag is replaced by the value of the div tag. The original value of the div tag is for demonstration purposes. This is a good separation of the front and back ends. This means that the content of the div tag is replaced by the value of the expression ${session.book}, regardless of what it is in the template. The reason it is "stuffed" in the template is so that it can be displayed as a prototype in the browser. ${user.id}; ${user.id}; ${user.id}; ${user.id}; Nice loop<li th:each="book : ${books}" >
Copy the code

3.URL expressions (introducing urls)

The point! The point! The point!

  • References to static resource files (CSS uses th:href, js uses th: SRC)

  • Href link URL(use th:href)

    Href = /seconddemo/ /seconddemo/usethymeleaf? Name =Dear Relative path with one argument /seconddemo/usethymeleaf? Name =Dear&alis=Dear Relative path with multiple parameters /seconddemo/usethymeleaf? Name = Dear&alis = Dear relative path with multiple parameters/seconddemo/usethymeleaf/Dear relative path, a variable to replace the URL/seconddemo/usethymeleaf/Dear/Dear relative path, @{/usethymeleaf} is the relative path of the Context. ${/usethymeleaf} is the path of the Context. The render will automatically add the current Web application Context name, assuming the Context name is secondDemo, then the result should be/secondDemo /usethymeleaf, Paths that start with a/(e.g. /usethymeleaf will add the server address and domain name and the application cotextPath to form the complete URL. Th :href attribute modifier: This calculates and replaces the value of the URL using the href link and puts it in the href attribute. 5. Th: Use the static address directly in hrefCopy the code

4. Select or asterisk expressions

Expressions are much like variable expressions, except that they use a pre-selected object instead of a context variable container (map) to execute *{customer.name}

<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>/ / equivalent to the<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>
Copy the code
1. Without considering the context, there is no difference between the two; The asterisk syntax evaluation is expressed on the selected object, not the entire context. What is the selected object? That's the value of the parent tag. The *{title} expression above can be understood as ${book.title}. 2. Of course, the dollar sign and asterisk syntax can be mixedCopy the code

Th.attr = “Attribute name = attribute value”, see section 7. Set property Values section

5. Text internationalization expressions

A literal internationalization expression allows us to get the locale literal information (.properties) from an external file, index Value with Key, and optionally provide a set of parameters.

#{main.title} #{message.entrycreated(${entryId})} this expression can be found in the template file:<table>
    <th th:text="#{header.address.city}">
    <th th:text="#{header.address.country}">
</table>
Copy the code

6. Syntax supported by 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
  • Text operations

    • String concatenation: +

    • Textual substitution (Literal substitutions) : | The name is ${name} |

      <div th:class="'content'">.</div>
      <span th:text="|Welcome to our application, ${user.name}! |">
      //Which is equivalent to:
      <span th:text="'Welcome to our application, ' + ${user.name} + '! '">
      <span th:text="${onevar} + ' ' + |${twovar}, ${threevar}|">
      Copy the code
  • (4) Arithmetic operations

    • Binary operators: +, -, *, /, %
    • Minus sign (unary operator) : –
  • Boolean operations

    • Binary operators: and , or
    • Boolean negation (unary operator): ! , not
  • Word order and Equality

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

    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ? : (defaultvalue)
    Example 1:<h2 th:text="${expression} ? 'Hello' : 'Something else'"></h2>Example 2:<! -- IF CUSTOMER IS ANONYMOUS -->    
    <div th:if="${customer.anonymous}">        
        <div>Welcome, Gues!</div>    
    </div>    
    <! -- ELSE -->    
    <div th:unless="${customer.anonymous}">        
        <div th:text=" 'Hi,' + ${customer.name}">Hi, User</div>    
    </div>
    Copy the code
  • Special tokens:

    • No-Operation: _
  • switch

  • cycle

    Rendering list data is a very common scenario. For example, there are now n records that need to be rendered into a table or LI list tag. The data set must be traversable, using the TH :each tag

    Code analysis: loop, add th:each= "value:${list}" attributes to HTML tags, such as iterating over proDS data or loop with state variables:Copy the code

Use state variables to judge:

7. Set the property value

Th :attr Any attribute value, syntax: th:attr=" attribute name = attribute value,[attribute name = attribute value]" Attribute value if using expressions: There are usually URL expressions @{} and variable expressions ${}, but this tag syntax is not very elegant examples: Th :action :attr=" SRC =@{/images/gtvglogo.png},title=#{logo}, Alt =#{logo}" Th: SRC th:attr="value=#{subscribe. Submit}<input type="checkbox" name="active" th:attr="checked=${user.active}"/>At the same time, two special properties can be set like this: th:alt-title and th: lang-Xmllang th: SRC ="@{/images/ gtvGlogo.png}" th: Alt-title ="#{logo}" 2. Th: attrAppEnd =" BTN "th: attrAppend ="class=${" + cssStyle}" class="btn warning" 3. There are also two specific add attributes th: classAppEnd and th: styleAppEnd class="row" th: classAppend ="${prodStat. Odd}? 'odd'" class="row odd", even row class="row"Copy the code

8.Built-in variable Utilities

To make templates easier to use, Thymeleaf also provides a series of Utility objects (built into the Context) that can be accessed directly via #.

dates : java.util.Date function method class
calendars : Similar to #dates, for java.util.calendar
numbers : A function method class that formats numbers
strings : The function of a string object class, the contains, startWiths, prepending/appending etc
objects: Function class operations on objects
bools: A functional method of evaluating a Boolean value
Arrays: Functional class methods for arrays   
lists: Lists function class method
sets   
maps
Copy the code
Code examples:  ${#dates.format(dateVar, 'dd/MMM/yyyy HH:mm')} ${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')} ${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')} ${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')} ${#dates.createNow()} ${#dates.createToday()} ${#strings.isEmpty(name)} ${#strings.arrayIsEmpty(nameArr)} ${#strings.listIsEmpty(nameList)} ${#strings.setIsEmpty(nameSet)} ${#strings.startsWith(name,'Don')} // also array*, list* and set* ${#strings.endsWith(name,endingFragment)} // also array*, list* and set* ${#strings.length(str)} ${#strings.equals(str)} ${#strings.equalsIgnoreCase(str)} ${#strings.concat(str)} The ${# strings. ConcatReplaceNulls (STR)} ${# strings. RandomAlphanumeric (count)} / / generate a random stringCopy the code

9. Thymeleaf layout

10. The appendix

Thymeleaf_3.0.5 Chinese Reference Manual Extraction code: EMK0