九、局部变量
Thymeleaf 将“局部变量”称为为模板的特定片段定义的变量,这些变量仅可用于该片段内部的评估。
我们已经看到的示例是产品列表页面中的prod
iter 变量:
<tr th:each="prod : ${prods}">
...
</tr>
该prod
变量仅在<tr>
标记的范围内可用。特别:
- 该标记可用于在该标签中执行的所有其他
th:*
属性,其优先级小于th:each
(这意味着它们将在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
变量将作为局部变量创建并添加到来自上下文的变量 Map 中,以便它可以与上下文中声明的任何其他变量一起用于求值,但只能在包含变量的范围内<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
具有更高的precedence
,我们可以在span
标签中解决所有问题:
<p>
Today is:
<span th:with="df=#{date.format}"
th:text="${#calendars.format(today,df)}">13 February 2011</span>
</p>
您可能在想:优先?我们还没有谈论这个!好吧,不用担心,因为这正是下一章的内容。
最新评论
徒弟可以A师傅,学生可以A老师,为什么外包不能A正式,我觉得很正常。异性相吸这是宇宙真理
PHP天下第一(狗头叼花)
第一个不需要关注公主号直接给激活码的帖子!
客户端超时断开后,服务端如果没有设置超时机制,那也会继续等待处理,万一这期间有消息到了,那不是就接受到消息处理了,但是也没有办法返回到客户端,导致消息丢失。
企业级GO项目开发实战 Kubernetes权威指南 第六版
https://pan.baidu.com/s/1q3bnTncIACKoTZFxvx7BQw?pwd=ii7n
RabbitMQ精讲,项目驱动落地,分布式事务拔高 有吗?
Spring Cloud Alibaba 微服务架构实战 https://pan.baidu.com/s/1jF5voFRoeF0lYAzAPBWSbw?pwd=chqk