The use of Thymeleaf templates and integration with Spring Boot

A new generation of Java template engine Thymeleaf

Reference:  http://www.tianmaying.com/tutorial/using-thymeleaf

http://blog.csdn.net/u012706811/article/details/52185345

 

Thymeleaf is a template engine for rendering XML/XHTML/HTML5 content. Similar to JSP, Velocity, FreeMaker, etc., it can also be easily integrated with Web frameworks such as Spring MVC as a template engine for Web applications. Compared with other template engines, the biggest feature of Thymeleaf is that it can directly open and display template pages in the browser without starting the entire web application.

 

1. Introduce dependencies

Direct introduction in maven

 

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
 

You can view the dependencies and find that spring-boot-starter-web has been included under spring-boot-starter-thymeleaf, so you can remove the dependency of spring-boot-starter-web.

2. Configure the view resolver

Many configurations of spring-boot have default configurations. For example, the default page mapping path is 
classpath:/templates/*.html 
, and the static file path is 
classpath:/static/

thymeleaf template parser properties can be configured in application.properties. Just like JSP parser configuration with springMVC

#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#Close the cache during development, otherwise you won't be able to see the real-time page
spring.thymeleaf.cache=false
#thymeleaf end

 

The specific parameters that can be configured can be viewed in 
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafPropertiesthis class. The above configuration is actually the attribute value injected into the class.

3. Write DEMO

1. Controller

    @Controller
    public class HelloController {

        private Logger logger = LoggerFactory.getLogger (HelloController.class);
        /**
         * test hello
         * @return
         */
        @RequestMapping(value = "/hello",method = RequestMethod.GET)
        public String hello(Model model) {
            model.addAttribute("name", "Dear");
            return "hello";
        }

    }

 

2.view (annotation is the index generated by IDEA, which is convenient for IDEA to complete)

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<!--/*@thymesVar id="name" type="java.lang.String"*/-->
<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>
</body>
</html>

 

3. Effects

write picture description here

4. Basic grammar

Recalling the above DEMO, it can be seen that the first thing to do is to rewrite the html tag

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

Only then can this syntax be used in other tags th:*. This is the premise of the following syntax.

1. Get the variable value

<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>

It can be seen that symbols are used to obtain variable values &. For javaBeans, the 变量名.属性名way to use them is the same as that of EL expressions.

In addition $, the expression can only be written inside the th tag, otherwise it will not take effect. The above example is to use th:textthe value of the tag to replace the value in pthe tag. As for the original value in p, it is only for display in front-end development . In this case It is very good to separate the front and back ends.

2. Introduce URL

Thymeleaf handles URLs with the syntax @{…}

<a th:href="@{http://blog.csdn.net/u012706811}">绝对路径</a>
<a th:href="@{/}">相对路径</a>
<a th:href="@{css/bootstrap.min.css}">Content路径,默认访问static下的css文件夹</a>

Similar tags are: th:hrefandth:src

3. String replacement

In many cases, we only need to replace a certain place in a large piece of text, which can be done by string concatenation:

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

A more concise way is:

<span th:text="|Welcome to our application, ${user.name}!|">

Of course, this form has many restrictions. |…| can only contain variable expressions ${…}, and cannot contain other constants, conditional expressions, etc.

4. Operators

Various arithmetic operators can be used in expressions, such as +, -, *, /, %

th:with="isEven=(${prodStat.count} % 2 == 0)"

Logical operators >, <, <=,>=, ==, != can be used, the only thing to note is that <,> requires its HTML escape character :

    th:if="${prodStat.count} &gt; 1"
    th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"

5. Conditions

if/unless

Thymeleaf uses the th:if and th:unless attributes for conditional judgment. In the following example, the label is only displayed when the condition in th:if is true:

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

th:unless is the opposite of th:if, and its content is displayed only if the condition in the expression is not satisfied.

Switch

Thymeleaf also supports multiplexing Switch structures:

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
</div>

The default attribute default can be represented by *:

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

6. Loop

Rendering list data is a very common scenario. For example, now there are n records that need to be rendered into a table

, the data collection must be traversable, using the th:each tag:

 

<body>
  <h1>Product list</h1>

  <table>
    <tr>
      <th>NAME</th>
      <th>PRICE</th>
      <th>IN STOCK</th>
    </tr>
    <tr th:each="prod : ${prods}">
      <td th:text="${prod.name}">Onions</td>
      <td th:text="${prod.price}">2.41</td>
      <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    </tr>
  </table>

  <p>
    <a href="../home.html" th:href="@{/}">Return to home</a>
  </p>
</body>

As you can see, you need to add the th:each tag to the element to be rendered in the loop (here), where th:each=”prod : ${prods}” means to traverse the collection variable prods, and the loop variable is prod in the loop The body can be accessed by expressions.

7.Utilities

In order to make the template easier to use, Thymeleaf also provides a series of Utility objects (built in Context), which can be accessed directly through #:

  • #dates
  • #calendars
  • #numbers
  • #strings
  • arrays
  • lists
  • sets
  • maps
  • ... 
    The following uses a piece of code to illustrate some commonly used methods:

date

/*
 * Format date with the specified pattern
 * Also works with arrays, lists or sets
 */
${#dates.format(date, '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')}

/*
 * Create a date (java.util.Date) object for the current date and time
 */
${#dates.createNow()}

/*
 * Create a date (java.util.Date) object for the current date (time set to 00:00)
 */
${#dates.createToday()}

string

/*
 * Check whether a String is empty (or null). Performs a trim() operation before check
 * Also works with arrays, lists or sets
 */
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}

/*
 * Check whether a String starts or ends with a fragment
 * Also works with arrays, lists or sets
 */
${#strings.startsWith(name,'Don')}                  // also array*, list* and set*
${#strings.endsWith(name,endingFragment)}           // also array*, list* and set*

/*
 * Compute length
 * Also works with arrays, lists or sets
 */
${#strings.length(str)}

/*
 * Null-safe comparison and concatenation
 */
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}

/*
 * Random
 */
${#strings.randomAlphanumeric(count)}

 

 

Replenish

After spring-boot1.4, thymeleaf3 is supported, and the version number can be changed to modify the support. 
Compared with 2, 3 greatly improves the efficiency, and does not require label closure. Similar links, img, etc. are well supported , configure as follows

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- set thymeleaf version -->
    <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
    <!--set java version-->
    <java.version>1.8</java.version>
  </properties>
 
 

 

 

 

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326749017&siteId=291194637