[Spring]Thymeleaf——XML/XHTML/HTML5模板引擎

什么是Thymeleaf?

Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
官方文档


使用

Maven依赖


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>

application.yml配置

  • cache : 设置thymeleaf的缓存。默认true,用于测试。
  • encoding : 编码
  • prefix : classpath:/templates/,模板文件路径
spring:
  thymeleaf:
    cache: false
    encoding: UTF-8

创建html

在resources/templates/目录中创建xxx.html。
这里创建了hello.html。

DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>titletitle>
head>
<body>
	
	<div th:text="${key}">div>
body>
html>

Controller返回页面

@Controller
@RequestMapping("/test")
public class TestController {

    /**
    * 访问test/hello,返回hello.html
    */
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("key","hello world");
        return "hello";
    }
}

常用标签

标签 作用
th:id 替换id
th:text 文本替换
th:utext 支持html的文本替换
th:object 替换对象
th:value 替换值
th:each 迭代
th:href 替换超链接
th:src 替换资源

取值

${Key}

循环
<ul th:each="item:${MyList}">
    <li th:text="${item}">li>
ul>

引入资源

@{资源地址}

读取配置文件中数据

#{key}

引用公共页面

  • th:insert:将代码块片段整个插入到使用了 th:insert 属性的 HTML 标签中;
  • th:replace:将代码块片段整个替换使用了 th:replace 属性的 HTML 标签中;
  • th:include:将代码块片段包含的内容插入到使用了 th:include 属性的 HTML 标签中。

你可能感兴趣的:(Spring,JAVA,spring,xml,xhtml,thymeleaf,模板引擎)