Thymeleaf教程 (九) 局部變量

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

<tr th:each="prod : ${prods}">
...
</tr>
  • 1
  • 2
  • 3

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>
  • 1
  • 2
  • 3
  • 4
  • 5

當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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

此th:with支持重複使用已經定義的局部變量,如:

<div th:with="company=${user.company + ' Co.'},account=${accounts[company]}">...</div>
  • 1

讓我們使用局部變量來優化如下配置界面吧,尤其是日期格式化在下面多次用到的時候:

<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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

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

接下來我們修改上述模板:

<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>
  • 1
  • 2
  • 3
  • 4
  • 5

事實上,th:with的優先級高於th:text,所以我們可以合併起來用。如下:

<p>
Today is:
<span th:with="df=#{date.format}"
th:text="${#calendars.format(today,df)}">13 February 2011</span>
</p>
  • 1
  • 2
  • 3
  • 4
  • 5
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章