如果要在Thymeleaf模板中获取控制器传递过来的数据,需要使用th标签

1. 在Thymeleaf模板页面中引入th标签的命名空间



xmlns:th="http://www.thymeleaf.org"


2. th:text

在几乎所有的HTML双标签都可以使用th:text属性,将接收到的数据显示在标签的内容中



<p th:text="${url}"></p>
<label th:text="${userName}"></label>
<div th:text="${password}"></div>


3. th:inline内联

  • HTML内联


<p th:inline="text">图书名称:[[${book.bookName}]]</p>


  • CSS内联


<style type="text/css" th:inline="css">
.style1 {
color: [[${color}]];
}
</style>


  • JavaScript内联


<script type="text/javascript" th:inline="javascript">
alert([[${msg}]]);
</script>


4. th:object 和 *



<div th:object="${book}">
<p th:text="*{bookId}"></p>
<p th:text="*{bookName}"></p>
<p th:text="*{bookAuthor}"></p>
</div>


5. 碎片使用

5.1 碎片的概念

碎片,就是HTML片段,我们可以将多个页面中使用的相同的HTML标签部分单独定义,然后通过th:include可以在HTML网页中引入定义的碎片

Thymeleaf基本语法与使用_html

 

5.2 碎片使用案例

  • 定义碎片:th:fragment
  • 引用碎片:th:replace 和 th:include

两者区别:th:include只会将引用的碎片内的文本内容获取过来而不会获取其他的,比如:CSS样式、JS脚本之类的内容,但是th:replace不仅会获取引用碎片内的文本内容,而且会加载其CSS、JS等静态文件

Thymeleaf基本语法与使用_html_02