thymeleaf 局部变量、属性优先级、注释

九、局部变量(local variable)

之前在th:each中遇到过局部变量

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

其中prod就是局部变量。

除此之外,thymeleaf提供了另外一种声明方式,通过使用th:each,语法如下:

<div th:with="firstPer=${persons[0]}">
    <p>The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.</p>
</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>

Well, 我们想要 "MMMM dd'','' yyyy" 的日期格式,那么我们可以加下面的句子到 home_en.properties 

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

th:with优先级高于 th:text,所以我们可以放在一个标签内

 

十、属性优先级(Atrribute Precedence)

 十一、注释 (Comments and Blocks)

11.1  <!-- ... -->  同HTML/XML的注释

<!-- User info follows -->
<div th:text="${...}">
...
</div>

11.2 thymeleaf解析器注释 

thymeleaf解析的时候会被注释,静态打开时会显示

单行   <!--/*  ...   */-->

<!--/* This code will be removed at thymeleaf parsing time! */-->

多行时:

<!--/*-->

...

...

<!--/*-->
<!--/*-->
    <div>
        you can see me only before thymeleaf processes me!
    </div>
<!--*/-->

 

11.3 静态解析时被注释,thymeleaf解析时会移除<!--/*/ 和 /*/-->标签对,内容保留

<span>hello!</span>
<!--/*/
    <div th:text="${...}">
        ...
    </div>
/*/-->
<span>goodbye!</span>

这个注释在写th:block的时候很有用哦

<table>
    <!--/*/ <th:block th:each="user : ${users}"> /*/-->
    <tr>
        <td th:text="${user.login}">...</td>
        <td th:text="${user.name}">...</td>
    </tr>
    <tr>
        <td colspan="2" th:text="${user.address}">...</td>
    </tr>
    <!--/*/ </th:block> /*/-->
</table>

11.4 th:block 适用于比如说要循环两个<tr>

it could be useful, for example, when creating iterated tables that require more than one <tr> for each element

 

posted @ 2016-06-17 17:48  nuoyi  阅读(8116)  评论(0编辑  收藏  举报