开发学院

您的位置:首页>教程>正文

教程正文

Thymeleaf 3.0教程:9 局部变量

  Thymeleaf将局部变量称为为模板的特定片段定义的变量,并且仅可用于该片段内的评估。

  我们已经看到的一个例子是产品列表页面中的产品变量:

<tr th:each="prod : ${prods}">
    ...
</tr>

  该生产变量仅在<tr>标记的范围内可用。具体来说:

  它将可用于在该标签中执行的任何其他th:*属性,其优先级低于th:每一个(这意味着它们将在th:each之后执行)。

  它将可用于<tr>标签的任何子元素,如任何<td>元素。

  Thymeleaf为您提供了一种无需迭代就可以使用th:with属性声明局部变量的方法,其语法类似于属性值赋值的语法:

<div th:with="firstPer=${persons[0]}">
  <p>
    The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
  </p>
</div>

  当th:with被处理时,firstPer变量被创建为一个局部变量,并被添加到来自上下文的变量映射中,以便它可以与上下文中声明的任何其他变量一起进行评估,但只能在包含<div>标记的边界内。

  您可以使用常用的多重赋值语法同时定义几个变量:

<div th:with="firstPer=${persons[0]},secondPer=${persons[1]}">
  <p>
    The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
  </p>
  <p>
    But the name of the second person is 
    <span th:text="${secondPer.name}">Marcus Antonius</span>.
  </p>
</div>

  th:with属性允许重用同一属性中定义的变量:

<div th:with="company=${user.company + ' Co.'},account=${accounts[company]}">...</div>

  让我们在杂货店的主页上使用这个,还记得我们为输出格式化日期写的代码吗?

<p>
  Today is: 
  <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 february 2011</span>
</p>

  如果我们希望"dd MMMM yyyy"实际上依赖于地区呢?例如,我们可能希望将以下消息添加到home_en.properties中:

date.format=MMMM dd'','' yyyy

  相当于我们的 home_es.properties:

date.format=dd ''de'' MMMM'','' yyyy

  现在,让我们使用th:with将本地化的日期格式转换为变量,然后在我们的th:text表达式中使用它:

<p th:with="df=#{date.format}">
  Today is: <span th:text="${#calendars.format(today,df)}">13 February 2011</span>
</p>

  那是干净简单的。事实上,鉴于th:with比th:text具有更高的优先级,我们可以在span标记中解决这一切:

                                                                                                                                        

  下一章我们将讨论属性优先级。