Spring Boot quick start Thymeleaf template engine basic use

introduce

Official website Introduction of

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.
With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.

Google Translate

Thymeleaf is a modern server-side Java template engine suitable for Web and stand-alone environments.
Thymeleaf's main goal is to bring elegant natural templates to your development workflow - HTML can be displayed correctly in the browser or used as a static prototype, so as to achieve more powerful collaboration among the development team.
With the modules of the Spring Framework, extensive integration with your favorite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern HTML5 JVM Web development - although it can do more.

Integrated Thymeleaf

Add dependency

Add dependency in Spring Boot project

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

Refresh maven

Test page

templates is the template for storing pages (which cannot be accessed externally and needs to be forwarded through the controller), and static is the file resource that can be accessed directly outside the static resource directory.

New index html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>home page</title>
</head>
<body>
home page....
</body>
</html>

Home controller IndexController

package org.example.mybatisplus.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * <h1></h1>
 *
 * @version 1.0
 * @author: Vincent Vic
 * @since: 2022/01/15
 */
@Controller
public class IndexController {

    @GetMapping("/")
    public String index(){
        return "index";
    }
}

http://localhost:8080/
Home page

Basic use

Value

Create commodity information web page goodinfo HTML, where xmlns:th is added using the header=“ http://www/thymeleaf.org ”, the value is marked with th:text

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www/thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Product list</title>
</head>
<body>
    Get a single value:<label th:text="${str}"></label>
    Get single value floating point:<label th:text="${price}"></label>
    <hr/>
    Get object (product information)
    <hr/>
    id:<label th:text="${good.id}"></label>
    name:<label th:text="${good.goodName}"></label>
    Price:<label th:text="${good.goodPrice}"></label>
    <hr/>

</body>
</html>

Write the controller GoodController to facilitate the writing of dead data here
Add value passing information through the addAttribute of the Model, which can be a single string, floating-point type, integer, floating-point type, object, etc., or a collection, key value pair, etc

package org.example.mybatisplus.demo.controller;


import org.example.mybatisplus.demo.entity.Good;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * <p>
 * Commodity table front end controller
 * </p>
 *
 * @author by Vincent Vic
 * @since 2022-01-14
 */
@Controller
@RequestMapping("/good")
public class GoodController {

    @GetMapping("get/{id}")
    public String getGood(@PathVariable("id")Integer id, Model model){
        //Add string information
        model.addAttribute("str","This is string information");
        //Add floating point
        model.addAttribute("price",32.2);
        //Add object
        Good good = new Good();
        good.setId(id);
        good.setGoodName("Intelligent mobile phone");
        good.setGoodPrice(new BigDecimal("5000.00"));
        model.addAttribute("good",good);

        return "goodInfo";
    }

}

The Good entity class used

package org.example.mybatisplus.demo.entity;

import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * <p>
 * Commodity list
 * </p>
 *
 * @author by Vincent Vic
 * @since 2022-01-14
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class Good implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * id
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * Trade name
     */
    private String goodName;

    /**
     * commodity price
     */
    private BigDecimal goodPrice;


}

http://localhost:8080/good/get/1
Get single value: This is string information get single value floating point: 32.2
Get object (product information)
id:1 Name: smartphone price: 5000.00

label

th:text

In almost all HTML double tags, the th:text tag can be used to display the received data in the content

<label th:text="${good.goodName}"></label>
<p th:text="${price}"></p>
<div th:text="${str}"></label>

th:inline inline tag

HTML inline

Implementation: Commodity Name: Smartphone

<label th:text="${good.goodName}">Trade name:</label>
<!-- If you write this, the code will overwrite the contents of the tag -->
Trade name: <label th:text="${good.goodName}"></label>
<!-- That's possible, but Thymeleaf Provided th:inline Tag properties can be implemented with -->
<label th:inline="text">Trade name:[[${good.goodName}]]</label>

Use the th:inline attribute setting, and the content needs to use '[[]]' double brackets to replace the EL expression ' ′ discharge stay his in Namely [ [ Put {} 'in it, i.e[[ 'in which [[{expression}]]

Style inline

Write some content, dynamic color, test code

<label class="style1">Show red</label>

Add a style label to the header to obtain the color passed by the controller. The controller passes the red parameter and omits the code

<style type="text/css" th:inline="css">
    .style1{
        color: [[${color}]];
    }
</style>

JavaScript inline

The use method is consistent with style inline

<script type="css/javascript" th:inline="javascript">

 </script>

th:object object label

th:object gets the object. As long as it is in the div, you can use '* {}' to directly get the value of the object attribute

<div th:object="${good}">
    id:<label th:text="*{id}"></label>
    name:<label th:text="*{goodName}"></label>
    Price:<label th:text="*{goodPrice}"></label>
    <hr/>
</div>

Test code

At goodinfo Modify based on HTML

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www/thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Product list</title>
    <style type="text/css" th:inline="css">
        .style1{
            color: [[${color}]];
        }
    </style>
</head>
<body>
    Get a single value:<label th:text="${str}"></label>
    Get single value floating point:<label th:text="${price}"></label>
    <hr/>
    Get object (product information)
    <hr/>
    id:<label th:text="${good.id}"></label>
    name:<label th:text="${good.goodName}"></label>
    Price:<label th:text="${good.goodPrice}"></label>
    <hr/>

    HTML Inline use:<label th:inline="text">Trade name: [[${good.goodName}]]</label><br/>
    Style inline use:<label class="style1">Show red</label>
    <hr/>
    th:object Attribute use
    <div th:object="${good}">
        id:<label th:text="*{id}"></label>
        name:<label th:text="*{goodName}"></label>
        Price:<label th:text="*{goodPrice}"></label>
        <hr/>
    </div>

</body>
</html>

Add in getGood method of GoodController

//Inline add attribute
//Transfer color
model.addAttribute("color","red");

http://localhost:8080/good/get/1
Note: This is only the web page text information, not the style effect
Get single value: This is string information get single value floating point: 32.2
Get object (product information)
id:1 Name: smartphone price: 5000.00
HTML inline use: Product Name: Smartphone
Style inline use: show red
th:object attribute usage
id:1 Name: smartphone price: 5000.00

Process control

th:each loop label

Use the th:each tag attribute to write the product list function
Add method in controller GoodController

@GetMapping("list")
    public String getGood(Model model){
        List<Good> list = new ArrayList<>();
        //Generate simulation data
        for (int i = 1; i <= 10 ; i++) {
            Good good = new Good();
            good.setId(i);
            good.setGoodName("Intelligent mobile phone X"+i);
            good.setGoodPrice(new BigDecimal("5"+(i%9)+"00.00"));
            list.add(good);
        }
        model.addAttribute("goods",list);
        return "goodList";
    }

Page template goodlist html

<table>
    <caption>Product list</caption>
    <thead>
    <tr>
        <th>number</th>
        <th>Trade name</th>
        <th>commodity price</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="good:${goods}">
        <td th:text="${good.id}"></td>
        <td th:text="${good.goodName}"></td>
        <td th:text="${good.goodPrice}"></td>
    </tr>
    </tbody>
</table>

http://localhost:8080/good/list
Product list
No. commodity name commodity price
1 smartphone X1 5100.00
2 smartphone X2 5200.00
3 smartphone X3 5300.00
4 smartphone X4 5400.00
5 smartphone X5 5500.00
6 smartphone X6 5600.00
7 smartphone X7 5700.00
8 smartphone X8 5800.00
9 smartphone X9 5000.00
10 smartphone X10 5100.00

Branch label

th:if judgment tag

th:if branch label: if the condition is not true, the label will not be displayed; if it is true, the label will be displayed
Modify the original commodity list page, add the commodity evaluation column, and use th:if to judge that the high-quality recommendation is displayed if it is less than 5500, otherwise, the price is high

<table>
    <caption>Product list</caption>
    <thead>
    <tr>
        <th>number</th>
        <th>Trade name</th>
        <th>commodity price</th>
        <th>Commodity evaluation</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="good:${goods}">
        <td th:text="${good.id}"></td>
        <td th:text="${good.goodName}"></td>
        <td th:text="${good.goodPrice}"></td>
        <td th:if="${good.goodPrice} < 5500" style="color: aqua">Boutique recommendation</td>
        <td th:if="${good.goodPrice} >= 5500" style="color: #Ff7700 "> high price</td>
    </tr>
    </tbody>
</table>

http://localhost:8080/good/list
Product list
No. commodity name commodity price commodity evaluation
1 smartphone X1 5100.00 boutique recommendation
2 smart phone X2 5200.00 boutique recommendation
3 smartphone x35300.00 boutique recommendation
4 smart phone X4 5400.00 boutique recommendation
5. The price of smart phone X5 5500.00 is on the high side
6. The price of smart phone X6 5600.00 is on the high side
7. The price of smartphone X7 5700.00 is on the high side
8. The price of smart phone X8 5800.00 is on the high side
9 smartphone X9 5000.00 boutique recommendation
10 smartphone X10 5100.00 boutique recommendation

th:switch select label

th:switch and th:case are used together
Still modify in the commodity list. If you take the price balance, you will get 0, 1 and 2, corresponding to the three cases respectively. Only three conditions are formed for the content for testing

<table>
    <caption>Product list</caption>
    <thead>
    <tr>
        <th>number</th>
        <th>Trade name</th>
        <th>commodity price</th>
        <th>Commodity evaluation</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="good:${goods}">
        <td th:text="${good.id}"></td>
        <td th:text="${good.goodName}"></td>
        <td th:text="${good.goodPrice}"></td>
<!--        <td th:if="${good.goodPrice} < 5500" style="color: aqua">Boutique recommendation</td>-->
<!--        <td th:if="${good.goodPrice} >= 5500" style="color: #Ff7700 "> high price < / td > -- >
        <td th:switch="${good.goodPrice}%3">
            <label th:case="0">Boutique recommendation</label>
            <label th:case="1">Hot commodity</label>
            <label th:case="2">Sales list</label>
        </td>
    </tr>
    </tbody>
</table>

Fragment use

When developing a website, we usually have the upper, middle and lower structure. The upper and lower contents are often the same, and only the content parts are different. Thymeleaf provides the function of introducing pages. You can extract the same page into a separate page and reference it on each page. If you modify the referenced page content, all referenced pages will also change.

Fragment definition

component/header.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www/thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>header</title>
</head>
<body>
<div th:fragment="header" style="background-color: aqua;color:white;width: 100%;height: 60px;">
    head
</div>
</body>
</html>

component/footer.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www/thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>footer</title>
</head>
<body>
<div th:fragment="footer" style="background-color: gainsboro;color:white;width: 100%;height: 60px;position: absolute;bottom: 0px;">
    bottom
</div>
</body>
</html>

introduce

Controller IndexController add jump

@GetMapping("/a")
public String a(){
    return "a";
}
@GetMapping("/b")
public String b(){
    return "b";
}

th:include

Write a.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www/thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>a page</title>
</head>
<body>

    <div th:include="component/header::header"></div>
    <div>
        content A
    </div>
    <div th:include="component/footer::footer"></div>
</body>
</html>

Test at this time

http://localhost:8080/a
head
Content A
bottom

No styles are displayed on the page. Through F12 inspection, it is found that th:include does not contain styles

<div>
    head
</div>
<div>
    content A
</div>
<div>
	bottom
</div>

th:replace

Change th:include to th:replace, run again, and the style will be

Keywords: Java Spring Spring Boot

Added by jayR on Wed, 19 Jan 2022 08:37:31 +0200