Thymeleaf语法
- ${}:访问thymeleaf命名空间内放着的变量
- *{}: 结合${}使用,可以直接去对象属性,而不用对象名.属性名,的方式。
- #{}: 结合 "th:text"使用,可以获得服务器内的静态资源,比如yml文件内定义的一些属性。或者获取图片等资源。
- 链接URL表达式:@{…}: 它可以连接到目录下的静态资源,也可以发起访问后端。
- 常用的对象表达式:“# +静态方法”。类似java的静态方法访问:
#dates: java.util的实用方法。对象:日期格式、组件提取等.
#calendars: 类似于#日期,但对于java.util。日历对象
#numbers: 格式化数字对象的实用方法。
#strings:字符串对象的实用方法:包含startsWith,将/附加等。
#objects: 实用方法的对象。
#bools: 布尔评价的实用方法。
#arrays: 数组的实用方法。
#lists: list集合。
#sets:set集合。
#maps: map集合。
#aggregates: 实用程序方法用于创建聚集在数组或集合.
#messages: 实用程序方法获取外部信息内部变量表达式,以同样的方式,因为他们将获得使用# {…}语法
#ids: 实用程序方法来处理可能重复的id属性(例如,由于迭代)。
#httpServletRequest:用于web应用中获取request请求的参数
#session:用于web应用中获取session的参数
- 常用属性:
th:action 表单提交的地址 <form action="subscribe.html" th:action="@{/subscribe}">
th:each 属性赋值 <tr th:each="user,userStat:${users}">
th:field 常用于表单字段绑定 <input type="text" value="" th:field="*{username}"></input>
th:href 链接地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:id 替换id <input th:id="'xxx' + ${collect.id}"/>
th:if 判断条件 <a th:if="${userId == collect.userId}" >
th:include 布局标签,替换内容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:fragment 布局标签,定义代码片段,其它引用 <div th:fragment="alert">
th:object 替换对象 <div th:object="${session.user}">
th:src 图片类地址引入 ![](@{/img/logo.png})
th:replace 布局标签,替换整个标签到引入的文件 <div th:replace="fragments/header :: title"></div>
th:text 文本替换 <p th:text="${collect.description}">description
th:value 属性赋值 <input th:value="${user.name}" />
th:inline 定义js脚本可以使用变量 <script type="text/javascript" th:inline="javascript">
th:remove 删除某个属性 <tr th:remove="all">
th:style 设置样式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick 点击事件 th:οnclick="'getCollect()'"
其中,
- th:inline 可以让你的js代码直接访问到thymeleaf空间内的对象,很好用。
<script th:inline="javascript">
//提交表单
function form_submit() {
var data={
userId:[[${userId}]], //js引用后端传来的值
role:[[${role}]],
password:$("#password").val(),
}
$.post("xx",data,function (mes) {
...xxx...
})
- th:object和th:field:一起用来绑定表单数据。 th:object:用于表单数据对象绑定,将表单绑定到后台controller的一个JavaBean参数。其实直接name,id之类的,后端也可以反射进行赋值的。
- th:if:条件判断。如果为否则标签不显示
- 标准表达式
- 字面:文本文字:放在 单引号 里面,可以是任意字符,如:‘one text’,‘Another one!’,…
<span th:text="'working web application'">
- 文字替代: 有两种方式:一个是|The name is ${name}|,另一个是+号连接:
<span th:text="|Welcome to our application, ${user.name}!|">
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
- 运算符:都是双引号下使用,就会被视为运算,被单引号括住就作为字符了。
- 二元运算符:+,-,*,/,%
- 布尔运算:and,or,not
- 比较和相等:>,<,>=,<=(gt,lt,ge,le);==,!=(eq,ne)
- 条件运算符:IF-THEN: (if) ? (then)