使用${}取值的规则
- ${x} will return a variable x stored into the Thymeleaf context or as a request attribute.
- 将返回存储在Thymeleaf上下文中或作为请求属性的变量x。
- ${param.x} will return a request parameter called x (which might be multivalued).
- ${param.x}将返回一个名为x的请求参数(可能是多值的)。
- ${session.x} will return a session attribute called x .
- ${session.x}将返回名为x的会话属性。
- ${application.x} will return a servlet context attribute called x .
- ${application.x}将返回一个名为x的servlet上下文属性。
1.解析格式数据
- th:text :不会解析数据中的标签,而是把它当作一个纯文本
- th:utext:会解析数据中的标签
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" >
<title>Title</title>
</head>
<body>
<h2>Thymeleaf模板引擎解析的页面模板</h2>
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
</body>
</html>
package com.thhh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/test01")
public String test01(Model model){
model.addAttribute("msg","<h2 style=\"color: red\">test</h2>");
return "test";
}
}
2.循环遍历集合数据
- th:each
- 让controller返回一个list集合数据
@RequestMapping("/test01") public String test01(Model model){ model.addAttribute("msg","<h2 style=\"color: red\">test</h2>"); model.addAttribute("list", Arrays.asList("张三","李四","王五")); return "test"; }
- 页面模板使用th:each取出集合遍历数据
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" > <title>Title</title> </head> <body> <h2>Thymeleaf模板引擎解析的页面模板</h2> <div th:text="${msg}"></div> <div th:utext="${msg}"></div> <hr> <div th:each="user:${list}" th:text="${user}"></div> </body> </html>
- 还有另一种输出遍历对象的语法格式
<div th:each="user:${list}">[[${user}]]</div> 等效于 <div th:each="user:${list}" th:text="${user}"></div> 但是在实际开发中我们更多使用第二种