9 本地变量

Thymeleaf把定义在特定的模版片段里,只在那个片段里才有效的变量,称为本地变量。

我们已经看过一个例子,在产品列表页面的prod遍历变量:

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

那个prod变量只在<tr>标签里才有效。特别的:

  • 对在那个标签里执行的优先级低于th:each(也就是说它们将在th:each之后执行)的任何其它的th:*属性有效。
  • <tr>标签的任何子元素有效,比如<td>元素。

Thymeleaf提供了一种不使用遍历声明本地变量的方法————使用th:with属性,它的语法类似于属性值赋值:

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

th:with被处理,firstPer变量会被创建为一个本地变量,并加入到上下文的变量映射关系里。这样,它就和其它定义在上下文里的变量一样,能够求值,但只限于包含它的<div>标签里面。

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

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

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

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

让我们在杂货店的主页上使用一下!还记得我们用来格式化输入日期的代码吗?

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

如果我们想要"dd MMMM yyyy"实际上依赖本地化设置呢?比如,我们可能想要在home_en.properties里添加以下信息:

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

等价于我们的home_es.properties

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

现在,让我们使用th:with把本地化的日期格式放进变量里,然后在我们的th:text表达式里使用它:

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

这就干净简单多了。实际上,th:with优先级高于th:text。我们可以使用span标签解决:

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

你可能正在想:优先级是什么🤔?我们还没有讨论过它!不过,别担心,下一章讲的就是它。