Thymeleaf 局部变量

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

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

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

该prod变量仅在标记的范围内可用。特别:

  • 它将可用于th:* 在该标记中执行的任何其他属性,其优先级低于th:each(这意味着它们将在之后执行th:each)。
  • 它将可用于标记的任何子元素,例如任何元素。 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 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>
    

    让我们在Grocery的主页上使用它!还记得我们为输出格式化日期而编写的代码吗?

    <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具有较高的precedence比th:text,我们可以解决这一切的span标签:

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

    你可能会想:优先顺序?我们还没有谈过这个!好吧,不要担心,因为这正是下一章的内容。

th:* 在同一个标​​签中写入多个属性会发生什么?例如:<ul> <li th:each="item : ${items}" th:text="${item.description}"& ...