文本标签 th:text:
用于文本内容的显示操作。
th:text 进行文本替换 不会解析html
代码演示:
@RequestMapping("/th")
public String th(Model model){
String msg = "<h1>我是h1</h1>";
model.addAttribute("msg",msg);
return "/course/th";
}
th:text 进行文本替换 不会解析html
<p th:text="text标签: + ${msg}"></p>
结果页面:
<p>text标签:<h1>我是h1</h1></p>
{...}和 ${...}表达式:
正常情况下 {...} 和 ${...}是一样的,但是 *{...} 一般和 th:object 进行一起使用来完成对象属性的简写。
代码演示:
@RequestMapping("/th")
public String th(Model model){
User user = new User("ljk",18);
model.addAttribute("user",user);
return "/course/th";
}
使用 ${...}操作
模版代码:
<p th:text="${user.name}"></p><p th:text="${user.age}"></p>
结果页面:
<p>ljk</p><p>18</p>
**使用 *{...}操作**
模版代码:
<p th:text="*{user.name}"></p><p th:text="*{user.age}"></p>
结果页面:
<p>ljk</p><p>18</p>
**使用 *{...}特有操作**
模版代码:
<div th:object="${user}" >
<p th:text="*{name}"></p>
<p th:text="*{age}"></p></div>
结果页面:
<p>ljk</p><p>18</p>
~{...}片段表达式:
这个一般和模版布局的语法一起使用,具体使用方式请看下面模版布局的教程。
定义引用片段代码
我们可以通过 th:fragment 来定义引用片段,然后可以在其他页面进行引用。
定义footer.html页面 该页面就是我们的引用片段代码
<footer th:fragment="footer" class="ui inverted vertical segment m-padded-tb-massive m-opacity">
© 2011 The Good Thymes Virtual Grocery
</footer>
th:replace 插入引用片段的标签和内容:
如下面的代码2种方式的写法是一致的。如果你觉得~{footer :: copy}写法比较麻烦可以采用简写的方式footer :: copy。
<footer th:replace="_fragments::footer" class="ui inverted vertical segment m-padded-tb-massive m-opacity"> </footer>
<footer th:replace="~{_fragments::footer}"></footer>
@{...}链接网址表达式
一般和 th:href、th:src进行结合使用,用于显示Web 应用中的URL链接。通过@{...}表达式Thymeleaf 可以帮助我们拼接上web应用访问的全路径,同时我们可以通过()进行参数的拼接
代码演示:
模版代码:
<img th:src="@{/images/gtvglogo.png}" />
结果页面:
<img src="/sbe/images/gtvglogo.png">
模版代码:
<a th:href="@{/product/comments(prodId=${prod.id})}" >查看</a>
结果页面:
<a href="/sbe/product/comments?prodId=2">查看</a>
模版代码:
<a th:href="@{/product/comments(prodId=${prod.id},prodId2=${prod.id})}" >查看</a>
结果页面:
<a href="/sbe/product/comments?prodId=2&prodId2=2">查看</a>
条件判断 th:if/th:unless
th:if 当条件为true则显示。
th:unless 当条件为false 则显示。
代码演示:
java代码:
@GetMapping("/types")
public String Type( Model model){
model.addAttribute("message", true);
return "/admin/types";
}
模版页面:
<p th:if="${message}">if判断</p>
结果页面:
<p>if判断</p>
模版页面:
<p th:unless="!${message}">unless 判断</p>
结果页面:
<p>unless 判断</p>