Some common templating engines

JSP, Velocity, Freemarker, Thymeleaf

! [img](https://gitee.com/cn_moti/blog-image01/raw/master/ ## SpringBoot template engine Thymeleaf/image 19.png)

SpringBoot recommends Thymeleaf, which has simpler syntax and more power.

SpringBoot introduced thymeleaf

Add a dependency to a POM file

<! -- Introduce the Thymeleaf module engine -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-thymeleaf</artifactId>

        </dependency>

Copy the code

Thymeleaf website

Use SpringBoot thymeleaf

View the SpringBoot auto-configuration source code

@ConfigurationProperties(prefix = "spring.thymeleaf")

public class ThymeleafProperties {



 private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");



 private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");



 public static final String DEFAULT_PREFIX = "classpath:/templates/";



 public static final String DEFAULT_SUFFIX = ".html";

Copy the code

As soon as we put the HTML page in classpath:/templates/, thymeleaf will render it automatically

1. Import thymeleaf’s namespace: Add attributes to tags in HTML files:xmlns:th="http://www.thymeleaf.org"

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

Copy the code

2, write the Controller to jump to the page

/ * *

     * @returnJump to the classpath: / templates/success. HTML

* /

    @RequestMapping("/success")

    public String success(Map<String,Object> map){

        map.put("who"."moti");

        return "success";

    }

Copy the code

3. Write HTML files

<! DOCTYPE html>

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

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

<! --th:text sets the text content inside the div to -->

<span th:text="${who}"></span>! </h1>

</body>

</html>

Copy the code

Thymeleaf Grammar rules

1. Label priority

  • th:textChanges the text content of the current element
  • Th: any HTML attributeTo replace the value of the native property

! [img](https://gitee.com/cn_moti/blog-image01/raw/master/ ## SpringBoot template engine Thymeleaf/image-20.png)

2. Expressions

2.1 Simple Expressions

  • Variable Expressions: ${… } variable expression
  1. Gets the properties of the object and calls the methods
  2. Use the built-in base objects
  3. Use the built-in utility objects
# Built-in base objects

            #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.

# Some built-in utility objects

            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).

Copy the code
  • Selection Variable Expressions: * {… } select variable expression: is functionally the same as ${}

Th :object=”${session.user}”

<div th:object="${session.user}">

    <p>Name: <span th:text="*{userName}">Sebastian</span>.</p>

    <p>Age: <span th:text="*{age}">Pepper</span>.</p>

    <p>Sex: <span th:text="*{sex}">Saturn</span>.</p>

</div>

Copy the code
  • * * Message Expressions: # {… } Message expression: ** Get internationalized content
<h1 th:text="#{login.tip}">Please sign in</h1>

Copy the code
  • * * the Link URL Expressions: @ {… } Link URL expression: ** Define URL
@{/order/process(execId=${execId},execType='FAST')}

Copy the code
  • Fragments Expressions: ~ {… } fragment expression
<div th:insert="~{commons :: main}">... </div>

Copy the code

The word is 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...

Copy the code

2.3 Text Operations

     String concatenation: +

     Literal substitutions: |The name is ${name}|

Copy the code

(4) Arithmetic operations

Binary operators: + , - , * , / , %

Minus sign (unary operator): -

Copy the code

2.5 Boolean operations

Binary operators: and , or

Boolean negation (unary operator): ! , not

Copy the code

2.6 Order and Equality (comparative arithmetic)

Comparators: > , < , >= , <= ( gt , lt , ge , le )

Equality operators: == , ! = ( eq , ne )

Copy the code

2.7 Conditional Operators

If-then: (if)? (then)

If-then-else: (if)? (then) : (else)

Default: (value) ? : (defaultvalue)

Copy the code

2.8 Special tokens

No-Operation: _ 

Copy the code