Thymeleaf 常用属性

转载 · ITPSC · 2019-10-31 · 原文

1 常用属性

  • th:action
  • th:each
  • th:field
  • th:href
  • th:id
  • th:if
  • th:include
  • th:fragment
  • th:object
  • th:src
  • th:replace
  • th:text
  • th:value
  • th:class
  • th:onclick

2 常用表达式

  • ${}
  • *{}
  • #{}
  • @{}
  • #maps

一 常用属性

th:action

定义后台控制器路径,类似<form>标签的action属性。

例如:

<form id="login-form" th:action="@{/login}">...</form>

th:each

对象遍历,功能类似jstl中的<c:forEach>标签。

例如:

public class StudentRequestBean {

  private List<Student> students;
    ...
}

public class Student implements Serializable{

  private String firstName;

  private String school;

  ...
}


@RequestMapping(value = "/addStudent", method = RequestMethod.POST)

public String addStudent(@ModelAttribute(value = "stuReqBean") 

StudentRequestBean stuReqBean,ModelMap model) {...}
<form id="login-form" th:action="@{/addStudent}" 

th:object="${stuReqBean}" method="POST">

<div class="student" th:each="stuIter,rowStat:${stuReqBean.students}">

<input type="text" class="firstName" value="" 

th:field="*{students[__${rowStat.index}__].firstName}"></input>

<input type="text" class="school" value="" 

th:field="*{students[__${rowStat.index}__].school}"></input>

...

</div>

</form>

上面的例子中通过选择表达式*{}既能将表单绑定到后台的StudentRequestBean中的集合属性students,也能将Servlet上下文中的StudentRequestBean中的List类型的students变量回显,回显时通过 th:each 进行遍历。

注意1:绑定集合属性元素下标的用法*{students[${rowStat.index}].firstName}

注意2:如果List<Student> students为null,页面将无法显示表单,后台必须给students初始化一个值,即:

List<Student > stus = new ArrayList<Student >();

stus .add(new Student ());

StudentRequestBean.setStudents(stus );

注意3:stuIter代表students的迭代器

th:each="obj,iterStat:${objList}"

迭代对象可以是java.util.List,java.util.Map,数组等;
iterStat称作状态变量,属性有:

  • index:当前迭代对象的index(从0开始计算)
  • count: 当前迭代对象的index(从1开始计算)
  • size:被迭代对象的大小
  • current:当前迭代变量
  • even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算)
  • first:布尔值,当前循环是否是第一个
  • last:布尔值,当前循环是否是最后一个

th:field

常用于表单字段绑定。通常与th:object一起使用。 属性绑定、集合绑定。

如:

public class LoginBean implements Serializable{...

private String username;

private List<User> user;

...}


public class User implements Serializable{...

private String username;;

...}


@RequestMapping(value = "/login", method = RequestMethod.POST)

public String login(@ModelAttribute(value = "loginBean") LoginBean loginBean,ModelMap model) {..}
<form id="login-form" th:action="@{/login}" th:object="${loginBean}">...

<input type="text" value="" th:field="*{username}"></input>

<input type="text" value="" th:field="*{user[0].username}"></input>

</form>

th:href

定义超链接,类似<a>标签的href 属性。value形式为@{/logout}

例如:

<a th:href="@{/logout}" class="signOut"></a>

使用 <a th:href="@{/product/add}" target="_blank">产品</a>
可以得到 <a th:href="/product/add" target="_blank">产品</a>

使用 <a th:href="@{/product/show(skuid=${product.id})}" target="_blank">产品</a>
可以得到 <a th:href="/product/show?skuid=12" target="_blank">产品</a>

使用 <a th:href="@{'/product/show/'+${product.id}}" target="_blank">产品</a>
可以得到 <a th:href="/product/show/12" target="_blank">产品</a>

th:id

div id声明,类似html标签中的id属性。

例如:

<div class="student" th:id = "stu+(${rowStat.index}+1)"></div>

th:if

条件判断。

例如:

<div th:if="${rowStat.index} == 0">... do something ...</div>

th:include

见th:fragment

th:fragment

声明定义该属性的div为模板片段,常用与头文件、页尾文件的引入。常与 th:include, th:replace 一起使用。

例如:

声明模板片段/WEBINF/templates/footer. html

<div th: fragment=" copy" >

© 2011 The Good Thymes Virtual Grocery

</div>
引入模板片段

<div th: include=" /templates/footer : : copy" ></div>

<div th: replace=" /templates/footer : : copy" ></div>

th:object

用于表单数据对象绑定,将表单绑定到后台controller的一个JavaBean参数。常与th:field 一起使用进行表单数据绑定。

例如:

public class LoginBean implements Serializable{...}


@RequestMapping(value = "/login", method = RequestMethod.POST)

public String login(@ModelAttribute(value = "loginBean") LoginBean loginBean,ModelMap model) {...}
<form id="login-form" th:action="@{/login}" th:object="${loginBean}">...</form>

th:src

用于外部资源引入,类似于<script>标签的src属性,常与@{}一起使用。

例如:

<script th:src="@{/resources/js/jquery/jquery.json-2.4.min.js}"

th:replace

见 th:fragment

th:text

文本显示。如果要显示文本中的html内容使用 th:utext

例如:

<td class="text" th:text="${username}" ></td>

当前日期:<span th:text="${dt}"></span>超出平均值 <span th:text="${ratioPercent}+'%'"></span>,

th:value

用于标签复制,类似<option>标签的value属性。

例如:

<option th:value="Adult">Adult</option>

<input  id="msg" type="hidden" th:value="${msg}" />

th:class

样式标签

<a href="#" th:class="${user.type==1}? 'user' : 'admin'" th:text="${user.name}"></a>

th:onclick

https://www.jianshu.com/p/381e02c283f3
可能遇到的问题

org.thymeleaf.exceptions.TemplateProcessingException: Only variable expressions returning 
numbers or booleans are allowed in this context, any other datatypes are not trusted in the context of this expression, 
including Strings or any other object that could be rendered as a text literal. 
A typical case is HTML attributes for event handlers (e.g. "onload"), 
in which textual data from variables should better be output to "data-*" attributes and then 
read from the event handler. (template: "xxx" - line xx, col xx)

这是Thymeleaf语法问题
Thymeleaf获取值得方法:[[${xx.name}]],可以直接获取xx里面的name值

错误写法:th:onclick="'getName(\''+${person.name}+'\');'"
正确写法:th:onclick="getName([[${person.name}]]);"

二 常用表达式

地址:https://www.cnblogs.com/hjwublog/p/5051632.html

${}

变量表达式(美元表达式,哈哈),用于访问容器上下文环境中的变量,功能同jstl中${}。

<p><span th:text="${helloword}"></span></p>

*{}

选择表达式(星号表达式)。选择表达式与变量表达式有一个重要的区别:选择表达式计算的是选定的对象,而不是整个环境变量映射。也就是:只要是没有选择的对象,选择表达式与变量表达式的语法是完全一样的。那什么是选择的对象呢?是一个:th:object 对象属性绑定的对象。

<div th: obj ect=" ${session. user}" >

<p>Name: <span th: text=" *{firstName}" >Sebastian</span>. </p>

<p>Surname: <span th: text=" *{lastName}" >Pepper</span>. </p>

<p>Nationality: <span th: text=" *{nationality}" >Saturn</span>. </p>

</div>

上例中,选择表达式选择的是th:object 对象属性绑定的session. user对象中的属性。

#{}

消息表达式(井号表达式,资源表达式)。通常与th:text 属性一起使用,指明声明了th:text 的标签的文本是#{}中的key所对应的value,而标签内的文本将不会显示。

例如:

新建/WEB-INF/templates/home.html,段落

<p th: text=" #{home. welcome}" >This text will not be show! </p>

新建/WEB-INF/templates/home.properties,home.welcome:

home.welcome=this messages is from home.properties!

@{}

超链接url表达式。

例如:

<script th:src="@{/resources/js/jquery/jquery.json-2.4.min.js}"

#maps

工具对象表达式。常用于日期、集合、数组对象的访问。这些工具对象就像是java对象,可以访问对应java对象的方法来进行各种操作。

<div th:if="${#maps.size(stuReqBean.students[__${rowStat.index}__].score) != 0}">

<label>${score.key}:</label><input type="text" th:value="${score.value}"></input>

</div>

<div th:if="${#maps.isEmpty(stuReqBean.students[__${rowStat.index}__].score)}">

...do something...

</div>

其他工具对象表达式还有:

#dates
#calendars
#numbers 
#strings
#objects
#bools
#arrays
#lists
#sets