目录
Thymeleaf的变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和 JSTL 中的 ${} 相同,本篇总结标准表达式的用法以及注意事项。
一、标准变量表达式
1、使用形式
th:text="${}"
所有的表达式都必须嵌入在一个完整的html标签中,如完整的<span >、<div>中,使用前需要引入thymeleaf的命名空间
xmlns:th="http://www.thymeleaf.org"
当我们通过容器去解析时,如通过SpringMVC转发请求到thymeleaf页面中,表达式才生效,如果直接访问,表达式不生效
2、Controller
@RequestMapping(value="/demo")
public String demo(Model model){
model.addAttribute("message","hello springboot_thymeleaf!");
User user = new User();
user.setId("id1");
user.setName("arong");
model.addAttribute("user",user);
return "demo";
}
3、demo.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<hr>
<h5>标准变量表达式</h5>
<h5>字符串</h5>
<div th:text="${message}">消息</div>
<hr>
<h5>pojo类</h5>
<div th:text="${user.id}">pojo类</div>
<div th:text="${user.name}">pojo类</div>
<hr>
</body>
</html>
4、效果
二、选择变量表达式
当我们需要访问一个对象中的属性,我们其实并不需要每个都用${xx.xx}这样获得,而是通过选择变量表达式
th:object="${}"
th:text="*{}"
1、Controller
@RequestMapping(value="/demo")
public String demo(Model model){
model.addAttribute("message","hello springboot_thymeleaf!");
User user = new User();
user.setId("id1");
user.setName("arong");
model.addAttribute("user",user);
return "demo";
}
2、demo.html
<h5>pojo类(使用选择表达式)</h5>
<div th:object="${user}">
<div th:text="*{id}">pojo类</div>
<div th:text="*{name}">pojo类</div>
</div>
3、效果
三、URL表达式
URL表达式用法
href="info.html" th:href="@{'xxx'+${}}"
或者是采用更简单的方式去拼接路径
href="info.html" th:href="@{|xxx+${}|}"
1、Controller
model.addAttribute("user",user);
model.addAttribute("id","id");
2、demo.html
<h5>URL表达式</h5>
<a href="info.html" th:href="@{'/localhost:8080/'+${id}}">点击1</a>
<a href="info.html" th:href="@{|/localhost:8080/${id}|}">点击2</a>