Thymeleaf教程 (九) 局部变量

Thymeleaf的局部变量定义在模块里,并且只有在此模块生效。

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

prod 变量只有在此TR里才生效。

Thymeleaf提供一种定义变量的方式来取代迭代。

<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>
Nextday is:
<span th:text="${#calendars.format(nextday,'dd MMMM yyyy')}">13 february 2011</span>
</p>

首先日期的显示方式放在配置文件里home_zh.properties :

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

接下来我们修改上述模板:

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

事实上,th:with的优先级高于th:text,所以我们可以合并起来用。如下:

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

转载于:https://my.oschina.net/u/3346994/blog/1840005

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值