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>