Thymeleaf 教程

Thymeleaf 局部变量

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

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

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

prod 变量将只在 <tr> 标签的范围内可用。具体:

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

(2)它适用于该标签的任何子元素,例如任何 <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 MMM yyyy" 实际上取决于区域设置呢?例如,我们可能想在我们的 home_en.properties 中添加以下信息:

date.format=MMM 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 标签中解决这一切。

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

你可能在想。优先权?我们还没有谈及这个问题呢! 好吧,别担心,因为这正是下一章的内容。

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号