Thymeleaf模板引擎语法
一、简介
Thymeleaf是一种用于Web和独立环境的现代服务器端Java模板引擎。它拥有自然的模板功能,允许HTML以及XML文档用JavaScript的方式来进行合理的模块化。它是一个可扩展、全功能的引擎,而且是用与HTML/XHTML和XML/Java模板模板的源生、高度可读性的语法。
二、基本语法
1. 常用的命名空间:
1.1 如果HTML文件使用了命名空间,则在HTML标签中需要增加相应命名空间的标记
1.2 xmlns:th 在 顶层html标签中定义语句
1.3 xmlns:main 定义其他的元素标签中的应用
1.4 xmlns:layout 被layout功能使用时定义的应用
例:
```html
<!DOCTYPE html>
<html xmlns="" xmlns:th="">
```
2. 表达式语法:
2.1 表达式使用 th:text 定义
2.2 表达式将在页面展现为标签中的内容
2.3 使用形式:${...},如:
```html
<span th:text="${book.name}"></span>
```
3. 变量替换:
3.1 只要在表达式中使用了变量,可以调用变量的get方法
3.2 使用形式:${hod()},如:
```html
<span th:text="${Name()}"></span>
```
4. 选择语句:
4.1 当语句是真时使用 th:if 加上表达式
4.2 当语句是假时,使用 th:unless 加上表达式
```html
<p th:if="${book.published}">This book is published</p>
<p th:unless="${book.published}">This book is not published yet</p>
```
5. 循环语句:
5.1 使用 th:each 定义循环
5.2 使用 obj:目标 ,目标为变量,列表,数组等
5.3 如:
```html
<tr th:each="book : ${books}">
    <td th:text="${book.title}">On the Road</td>
</tr>
```
6. URL信息:
6.1 当用 th:href 定义超信息
6.2 使用变量和属性可以定义参数等
6.3 如:
```html
thymeleaf用法
<a th:href="{/order/process(execId=${execId},prodId=${prodId})}"
>View</a>
```
三、高级语法
1. 布局定义:
1.1 使用layout:fragment定义片段
1.2 使用th:fragment进行布局装饰
1.3 例如:在layout.html定义布局,在index.html定义内容
2. 页面片段装饰:
2.1 在layout.html中使用th:replace进行片段替换
2.2 在index.html中用layout:fragment定义片段
2.3 例:
```html
<div th:replace="fragments/header :: title">...</div>
```
3. 属性动态定义:
3.1 使用th:attr定义属性
3.2 例:
```html
<input type="text" th:attr="value=${user.name}"/>
```
4. 表单:
4.1 使用th:object和th:field引用对象
4.2 例:
```html
<form th:object="${user}" th:action="{/users}">
    <input type="text" th:field="*{name}" />
    <input type="text" th:field="*{age}" />

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。