Thymeleaf教程 (九) 局部變量

Thymeleaf的局部變量定義在模塊裏,而且只有在此模塊生效。優化

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

prod 變量只有在此TR裏才生效。spa

Thymeleaf提供一種定義變量的方式來取代迭代。code

<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內。orm

你同時能夠定義多個局部變量。如:it

<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支持重複使用已經定義的局部變量,如:form

<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,因此咱們能夠合併起來用。以下:date

<p>
Today is:
<span th:with="df=#{date.format}"
th:text="${#calendars.format(today,df)}">13 February 2011</span>
</p>
相關文章
相關標籤/搜索