Thymeleaf学习笔记(二)

缺省的Conversion

语法: ${{variable}}
含义: 默认调用转换函数,将其转换为string
示例:

<td th:text="${{user.lastAccessDate}}">...</td>

Preprocessing预处理

语法: ${#{artical.text{‘txtvar’)}}
含义: 在预处理阶段,替换为对应的message information,基于Locale
示例:

<p th:text="${__#{article.text('textVar')}__}">Some text here...</p>

设置节点属性

语法: th:attr=”attrname=#{abcd}”
含义: 设置节点中特定属性的值
示例:

<img src="../../images/gtvglogo.png" 
     th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

最终,img节点信息将被输出为:

<img src="/gtgv/images/gtvglogo.png" title="Logo de Good Thymes" alt="Logo de Good Thymes" />

这种方式是通用的做法;另外也可以通过th:attr_name来设置具体的属性信息。

Iteration

th:each 循环遍历
示例:

 <tr th:each="prod : ${prods}">
     <td th:text="${prod.name}">Onions</td>
     <td th:text="${prod.price}">2.41</td>
     <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
 </tr>

状态变量iterStat内置了如下若干个属性信息:

  • The current iteration index, starting with 0. This is the index property
  • The current iteration index, starting with 1. This is the count property.
  • The total amount of elements in the iterated variable. This is the size property.
  • The iter variable for each iteration. This is the current property.
  • Whether the current iteration is even or odd. These are the even/odd boolean properties.
  • Whether the current iteration is the first one. This is the first boolean property.
  • Whether the current iteration is the last one. This is the last boolean property.

示例如下:

<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

if/unless condition

说明: 条件判断,节点是否出现在页面中
示例:

  <td>
    <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
    <a href="comments.html" 
       th:href="@{/product/comments(prodId=${prod.id})}" 
       th:if="${not #lists.isEmpty(prod.comments)}">view</a>
  </td>

在上述示例中, #list代表内置的工具类, if语句在为true之时, 将显示这个链接地址

Switch 语句

说明: 多条件语句,类似在各类语句中一样
示例:

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

‘*’ 代表缺省的值,在所有的case都不满足的情况下,输出缺省值。

猜你喜欢

转载自blog.csdn.net/blueheart20/article/details/80990964
今日推荐