9ローカル変数
Thymeleafは、テンプレートの特定のフラグメントに対して定義され、このフラグメント内でのみ実行可能な変数をローカル変数と呼びます。
すでに見た例は、製品リストページのprod変数です。
<tr th:each="prod : ${prods}"> ... </tr>
このprod変数は、<tr>タグ内でのみ使用できます。 特に:
- このタグで実行されている他のth:*属性は、 th:eachよりも低い優先度で使用できます(つまり、th:eachの後に実行されます)
- <td>要素など、<tr>タグのすべての子要素で使用できます。
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変数はローカル変数として作成され、コンテキストに基づいて変数のリストに追加されるため、コンテキストで宣言されている他の変数とともに実行できますが、それを含む<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:テキスト式で使用します 。
<p th:with="df=#{date.format}"> Today is: <span th:text="${#calendars.format(today,df)}">13 February 2011</span> </p>
それはきれいで簡単でした。 実際、 th:withの方がth:textよりも優先度が高いという事実を考えると、spanタグでこれらすべてを解決できます 。
<p> Today is: <span th:with="df=#{date.format}" th:text="${#calendars.format(today,df)}">13 February 2011</span> </p>
あなたは思うかもしれません:優先度? これについてはまだ話していません! 心配しないでください。これは次の章で説明するとおりです。