Original words from the official website: Thymeleaf is a modern server-side Java template engine suitable for web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. Thymeleaf aims to provide a beautiful and easy-to-maintain way to create templates. It is modeled on natural templates and injects logic into template files in a way that does not affect the template as a design prototype. This improves design communication and bridges the gap between design and development teams. Thymeleaf is an HTML5 template engine for web application development. Thymeleaf provides an optional module for integrating Spring MVC. In application development, you can use Thymeleaf to completely replace JSP or other template engines, such as Velocity, FreeMarker, etc. The main purpose of Thymeleaf is to provide a way to create well-formatted templates that can be displayed correctly by browsers. thymeleaf template engine, replacing jsp.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
In application.yml Add the following code under spring: (which can make the changed page take effect in time and achieve a similar hot deployment effect):
#能让改动的页面及时生效,实现类似热部署效果 thymeleaf: cache: false
Pay attention to the indentation. After adding, the indentation is as follows:
Create an ordinary html file hello.html, as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> </html>
In Adding the namespace xmlns:th="http://www.thymeleaf.org"
to the html tag indicates that the page is a thymeleaf template page. That is, replace <html lang="en">
in the above code with In this way, you can use the th attribute in the tag on the page to retrieve the value in the model, similar to the EL expression. The specific usage code is as follows:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p th:text="'欢迎来到中国,我叫'+${name}+',今年'+${age}+'岁。'"></p> <p>欢迎来到中国,我叫<span th:text="${name}"></span>,今年<span th:text="${age}"></span>岁。</p> </body> </html>
ackage com.ysw.springboot01.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/thy") public class ThymeleafController { @RequestMapping("/hello") public String hello0(Model model){ //向model中存入数据 model.addAttribute("name","李白"); model.addAttribute("age","18"); //跳转到hello.html模版引擎 return "hello"; } }
The effect is as follows:
The above is the detailed content of How to use Thymeleaf templates in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!