[关闭]
@lirenmi 2017-08-12T09:19:08.000000Z 字数 19671 阅读 578

Thymeleaf学习摘要

thymeleaf


  1. <html xmlns:th="http://www.thymeleaf.org">

html 头部

  1. <p data-th-text="#{home.welcome}">Welcome to our grocery store!</p>

data-th-text

  1. <p th:utext="#{home.welcome}">Welcome to our grocery store!</p>

非转义

  1. <body>
  2. <p th:utext="#{home.welcome}">Welcome to our grocery store!</p>
  3. <p>Today is: <span th:text="${today}">13 February 2011</span></p>
  4. </body>

#{...}表示特定值,${...}表示变量

4 标准表达式语法

4.1 消息

  1. <p th:utext="#{home.welcome(${session.user.name})}">
  2. Welcome to our grocery store, Sebastian Pepper!
  3. </p>

可以传参数

4.2 变量

取值

  1. /*
  2. * . 对象取值一
  3. */
  4. ${person.father.name}
  5. /*
  6. * 对象取值二
  7. */
  8. ${person['father']['name']}
  9. /*
  10. * map
  11. */
  12. ${countriesByCode.ES}
  13. ${personsByName['Stephen Zucchini'].age}
  14. /*
  15. * 集合取值
  16. */
  17. ${personsArray[0].name}
  18. /*
  19. * 调用方法,可以用参数
  20. */
  21. ${person.createCompleteName()}
  22. ${person.createCompleteNameWithSeparator('-')}

基本对象:

例如:

  1. <span th:text="${#locale.country}">US</span>.

功能对象:

例如:

  1. <p>
  2. Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span>
  3. </p>

4.3 选择表达式

选择对象:th:object

  1. <div th:object="${session.user}">
  2. <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
  3. <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
  4. <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
  5. </div>

等价于:

  1. <div>
  2. <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
  3. <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  4. <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
  5. </div>

*$混用:

  1. <div th:object="${session.user}">
  2. <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
  3. <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  4. <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
  5. </div>

当一个对象的选择是在适当位置,所选择的对象也将提供给元表达式作为#object表达变量:

  1. <div th:object="${session.user}">
  2. <p>Name: <span th:text="${#object.firstName}">Sebastian</span>.</p>
  3. <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  4. <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
  5. </div>

至于说,如果没有对象的选择已经完成,美元和星号语法是等价的

  1. <div>
  2. <p>Name: <span th:text="*{session.user.name}">Sebastian</span>.</p>
  3. <p>Surname: <span th:text="*{session.user.surname}">Pepper</span>.</p>
  4. <p>Nationality: <span th:text="*{session.user.nationality}">Saturn</span>.</p>
  5. </div>
  1. <p>Please select an option</p>
  2. <ol>
  3. <li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>
  4. <li><a href="order/list.html" th:href="@{/order/list}">Order List</a></li>
  5. <li><a href="subscribe.html" th:href="@{/subscribe}">Subscribe to our Newsletter</a></li>
  6. <li><a href="userprofile.html" th:href="@{/userprofile}">See User Profile</a></li>
  7. </ol>
  1. <!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
  2. <a href="details.html"
  3. th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>
  4. <!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
  5. <a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
  6. <!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
  7. <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
  1. <a th:href="@{${url}(orderId=${o.id})}">view</a>
  2. <a th:href="@{'/details/'+${user.login}(orderId=${o.id})}">view</a>

4.6 字面

文本:

  1. <p>
  2. Now you are looking at a <span th:text="'working web application'">template file</span>.
  3. </p>

文本文字是单引号之间仅指定字符串,避免使用 ‘

数字:

  1. <p>The year is <span th:text="2013">1492</span>.</p>
  2. <p>In two years, it will be <span th:text="2013 + 2">1494</span>.</p>

布尔:

  1. <div th:if="${user.isAdmin()} == false"> ...

or

  1. <div th:if="${user.isAdmin() == false}"> ...

null:

  1. <div th:if="${variable.something} == null"> ...

文字标记:

  1. <div th:class="content">...</div>

代替:

  1. <div th:class="'content'">...</div>

4.7 追加文本

  1. <span th:text="'The name of the user is ' + ${user.name}">

4.8 文本替换

  1. <span th:text="|Welcome to our application, ${user.name}!|">

相当于:

  1. <span th:text="'Welcome to our application, ' + ${user.name} + '!'">

组合:

  1. <span th:text="${onevar} + ' ' + |${twovar}, ${threevar}|">

|...|内部只允许 ${...}*{...}#{...}

4.9 算数运算

  1. <div th:with="isEven=(${prodStat.count} % 2 == 0)">

OGNL

  1. <div th:with="isEven=${prodStat.count % 2 == 0}">

4.10 比较和相等

  1. <div th:if="${prodStat.count} &gt; 1">
  2. <span th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')">

别名:gt>), (lt),<( ),ge(),>= ()。 另外(),/ ()。le``<=``not``!``eq``==``neq``ne``!=

4.11 条件表达式

  1. <tr th:class="${row.even}? 'even' : 'odd'">
  2. ...
  3. </tr>

嵌套:

  1. <tr th:class="${row.even}? (${row.first}? 'first' : 'even') : 'odd'">
  2. ...
  3. </tr>

省略:

  1. <tr th:class="${row.even}? 'alt'">
  2. ...
  3. </tr>

4.12 默认表达式

  1. <div th:object="${session.user}">
  2. ...
  3. <p>Age: <span th:text="*{age}?: '(no age specified)'">27</span>.</p>
  4. </div>

等同于:

  1. <p>Age: <span th:text="*{age != null}? *{age} : '(no age specified)'">27</span>.</p>

括号内嵌套表达式:

  1. <p>
  2. Name:
  3. <span th:text="*{firstName}?: (*{admin}? 'Admin' : #{default.username})">Sebastian</span>
  4. </p>

4.13 无操作令牌

  1. <span th:text="${user.name} ?: _">no user authenticated</span>

等同

  1. <span th:text="${user.name} ?: 'no user authenticated'">...</span>

4.14 预处理

  1. <p th:text="${__#{article.text('textVar')}__}">Some text here...</p>

等价于

  1. <p th:text="${@myapp.translator.Translator@translateToFrench(textVar)}">Some text here...</p>

4.15 数据格式转换

  1. <td th:text="${{user.lastAccessDate}}">...</td>

${{...}} 转换为Calendar -> String

5 设置属性的值

5.1 设置任何属性的值

th:attr属性设置任何属性的值

  1. <form action="subscribe.html" th:attr="action=@{/subscribe}">
  2. <fieldset>
  3. <input type="text" name="email" />
  4. <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  5. </fieldset>
  6. </form>

多个属性:

  1. <img src="../../images/gtvglogo.png"
  2. th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

输出:

  1. <img src="/gtgv/images/gtvglogo.png" title="Logo de Good Thymes" alt="Logo de Good Thymes" />

5.2 设置特定属性的值

设置value属性,使用th:value

  1. <input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>

action

  1. <form action="subscribe.html" th:action="@{/subscribe}">

href:

  1. <li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>

各个html5的值

th:abbr th:accept th:accept-charset
th:accesskey th:action th:align
th:alt th:archive th:audio
th:autocomplete th:axis th:background
th:bgcolor th:border th:cellpadding
th:cellspacing th:challenge th:charset
th:cite th:class th:classid
th:codebase th:codetype th:cols
th:colspan th:compact th:content
th:contenteditable th:contextmenu th:data
th:datetime th:dir th:draggable
th:dropzone th:enctype th:for
th:form th:formaction th:formenctype
th:formmethod th:formtarget th:fragment
th:frame th:frameborder th:headers
th:height th:high th:href
th:hreflang th:hspace th:http-equiv
th:icon th:id th:inline
th:keytype th:kind th:label
th:lang th:list th:longdesc
th:low th:manifest th:marginheight
th:marginwidth th:max th:maxlength
th:media th:method th:min
th:name th:onabort th:onafterprint
th:onbeforeprint th:onbeforeunload th:onblur
th:oncanplay th:oncanplaythrough th:onchange
th:onclick th:oncontextmenu th:ondblclick
th:ondrag th:ondragend th:ondragenter
th:ondragleave th:ondragover th:ondragstart
th:ondrop th:ondurationchange th:onemptied
th:onended th:onerror th:onfocus
th:onformchange th:onforminput th:onhashchange
th:oninput th:oninvalid th:onkeydown
th:onkeypress th:onkeyup th:onload
th:onloadeddata th:onloadedmetadata th:onloadstart
th:onmessage th:onmousedown th:onmousemove
th:onmouseout th:onmouseover th:onmouseup
th:onmousewheel th:onoffline th:ononline
th:onpause th:onplay th:onplaying
th:onpopstate th:onprogress th:onratechange
th:onreadystatechange th:onredo th:onreset
th:onresize th:onscroll th:onseeked
th:onseeking th:onselect th:onshow
th:onstalled th:onstorage th:onsubmit
th:onsuspend th:ontimeupdate th:onundo
th:onunload th:onvolumechange th:onwaiting
th:optimum th:pattern th:placeholder
th:poster th:preload th:radiogroup
th:rel th:rev th:rows
th:rowspan th:rules th:sandbox
th:scheme th:scope th:scrolling
th:size th:sizes th:span
th:spellcheck th:src th:srclang
th:standby th:start th:step
th:style th:summary th:tabindex
th:target th:title th:type
th:usemap th:value th:valuetype
th:vspace th:width th:wrap
th:xmlbase th:xmllang th:xmlspace

5.3 同时设置多个值

  1. <img src="../../images/gtvglogo.png"
  2. th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

or

  1. <img src="../../images/gtvglogo.png"
  2. th:src="@{/images/gtvglogo.png}" th:title="#{logo}" th:alt="#{logo}" />

or

  1. <img src="../../images/gtvglogo.png"
  2. th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}" />

5.4 前缀和后缀

th:attrappendth:attrprepend属性

  1. <input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" />

cssStyle设置为变量"warning",你会得到:

  1. <input type="button" value="Do it!" class="btn warning" />

th:classappendth:styleappend属性专门用于添加CSS类和style样式:

  1. <tr th:each="prod : ${prods}" class="row" th:classappend="${prodStat.odd}? 'odd'">

5.5 布尔属性固定值

例如checked

  1. <input type="checkbox" name="active" th:checked="${user.active}" />

固定值布尔属性

th:async th:autofocus th:autoplay
th:checked th:controls th:declare
th:default th:defer th:disabled
th:formnovalidate th:hidden th:ismap
th:loop th:multiple th:novalidate
th:nowrap th:open th:pubdate
th:readonly th:required th:reversed
th:scoped th:seamless th:selected

5.6 设置任何属性的值

  1. <span th:whatever="${user.name}">...</span>

导致:

  1. <span whatever="John Apricot">...</span>

5.7 HTML5属性的友好支持

  1. <table>
  2. <tr data-th-each="user : ${users}">
  3. <td data-th-text="${user.login}">...</td>
  4. <td data-th-text="${user.name}">...</td>
  5. </tr>
  6. </table>

6 迭代

th:each属性:

  1. <tr th:each="prod : ${prods}">
  2. <td th:text="${prod.name}">Onions</td>
  3. <td th:text="${prod.price}">2.41</td>
  4. <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  5. </tr>

可迭代值:

6.2 状态变量

状态变量:iterStat

  1. <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
  2. <td th:text="${prod.name}">Onions</td>
  3. <td th:text="${prod.price}">2.41</td>
  4. <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  5. </tr>

如果你没有明确设置状态变量,Thymeleaf总是会被后面添加为您创建一个Stat到迭代变量的名称:

  1. <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
  2. <td th:text="${prod.name}">Onions</td>
  3. <td th:text="${prod.price}">2.41</td>
  4. <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  5. </tr>

7 判断

7.1 if and unless

th:if`属性:

  1. <a href="comments.html"
  2. th:href="@{/product/comments(prodId=${prod.id})}"
  3. th:if="${not #lists.isEmpty(prod.comments)}">view</a>

th:if逆属性th:unless:

  1. <a href="comments.html"
  2. th:href="@{/comments(prodId=${prod.id})}"
  3. th:unless="${#lists.isEmpty(prod.comments)}">view</a>

7.2 switch

th:switch/ th:case属性

  1. <div th:switch="${user.role}">
  2. <p th:case="'admin'">User is an administrator</p>
  3. <p th:case="#{roles.manager}">User is a manager</p>
  4. <p th:case="*">User is some other thing</p>
  5. </div>

默认选项被指定为th:case="*"

8 布局模板

8.1 包含模板片段

定义和引用片段:

定义片段:th:fragment属性

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <body>
  4. <div th:fragment="copy">
  5. &copy; 2011 The Good Thymes Virtual Grocery
  6. </div>
  7. </body>
  8. </html>

引用片段copy,使用th:insertth:replace属性

  1. <body>
  2. ...
  3. <div th:insert="~{footer :: copy}"></div>
  4. </body>

or

  1. <body>
  2. ...
  3. <div th:insert="footer :: copy"></div>
  4. </body>

选择条件

  1. <div th:insert="footer :: (${user.isAdmin}? #{footer.admin} : #{footer.normaluser})"></div>

不使用th:fragment引入:

  1. ...
  2. <div id="copy-section">
  3. &copy; 2011 The Good Thymes Virtual Grocery
  4. </div>
  5. ...

使用id属性引入

  1. <body>
  2. ...
  3. <div th:insert="~{footer :: #copy-section}"></div>
  4. </body>

th:insertth:replace之间的区别

例如

定义:

  1. <footer th:fragment="copy">
  2. &copy; 2011 The Good Thymes Virtual Grocery
  3. </footer>

引用:

  1. <body>
  2. ...
  3. <div th:insert="footer :: copy"></div>
  4. <div th:replace="footer :: copy"></div>
  5. <div th:include="footer :: copy"></div>
  6. </body>

结果:

  1. <body>
  2. ...
  3. <div>
  4. <footer>
  5. &copy; 2011 The Good Thymes Virtual Grocery
  6. </footer>
  7. </div>
  8. <footer>
  9. &copy; 2011 The Good Thymes Virtual Grocery
  10. </footer>
  11. <div>
  12. &copy; 2011 The Good Thymes Virtual Grocery
  13. </div>
  14. </body>

8.2 可参数化的片段签名

定义:

  1. <div th:fragment="frag (onevar,twovar)">
  2. <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
  3. </div>

引用:二选一

  1. <div th:replace="::frag (${value1},${value2})">...</div>
  2. <div th:replace="::frag (onevar=${value1},twovar=${value2})">...</div>

or:

  1. <div th:replace="::frag (twovar=${value2},onevar=${value1})">...</div>

不带片段参数的片段局部变量

即使没有定义参数:

  1. <div th:fragment="frag">
  2. ...
  3. </div>

可以使用上面指定的第二个语法来调用它们(只有第二个语法):

  1. <div th:replace="::frag (onevar=${value1},twovar=${value2})">

这将相当于组合th:replaceth:with

  1. <div th:replace="::frag" th:with="onevar=${value1},twovar=${value2}">

th:assert断言

  1. <div th:assert="${onevar},(${twovar} != 43)">...</div>

这有助于验证片段签名中的参数:

  1. <header th:fragment="contentheader(title)" th:assert="${!#strings.isEmpty(title)}">...</header>

8.3 灵活的布局:不仅仅是片段插入

定义

  1. <head th:fragment="common_header(title,links)">
  2. <title th:replace="${title}">The awesome application</title>
  3. <!-- Common styles and scripts -->
  4. <link rel="stylesheet" type="text/css" media="all" th:href="@{/css/awesomeapp.css}">
  5. <link rel="shortcut icon" th:href="@{/images/favicon.ico}">
  6. <script type="text/javascript" th:src="@{/sh/scripts/codebase.js}"></script>
  7. <!--/* Per-page placeholder for additional links */-->
  8. <th:block th:replace="${links}" />
  9. </head>

引入:

  1. ...
  2. <head th:replace="base :: common_header(~{::title},~{::link})">
  3. <title>Awesome - Main</title>
  4. <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
  5. <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
  6. </head>
  7. ...

结果:

  1. ...
  2. <head>
  3. <title>Awesome - Main</title>
  4. <!-- Common styles and scripts -->
  5. <link rel="stylesheet" type="text/css" media="all" href="/awe/css/awesomeapp.css">
  6. <link rel="shortcut icon" href="/awe/images/favicon.ico">
  7. <script type="text/javascript" src="/awe/sh/scripts/codebase.js"></script>
  8. <link rel="stylesheet" href="/awe/css/bootstrap.min.css">
  9. <link rel="stylesheet" href="/awe/themes/smoothness/jquery-ui.css">
  10. </head>
  11. ...

使用空片段

一个特殊的片段表达式,空的fragment()可以用来指定没有标记。

  1. <head th:replace="base :: common_header(~{::title},~{})">
  2. <title>Awesome - Main</title>
  3. </head>
  4. ...

注意如何片段的(第二个参数links)被设定为空的片段,并且因此没有被用于写入的<th:block th:replace="${links}" />块:

  1. ...
  2. <head>
  3. <title>Awesome - Main</title>
  4. <!-- Common styles and scripts -->
  5. <link rel="stylesheet" type="text/css" media="all" href="/awe/css/awesomeapp.css">
  6. <link rel="shortcut icon" href="/awe/images/favicon.ico">
  7. <script type="text/javascript" src="/awe/sh/scripts/codebase.js"></script>
  8. </head>
  9. ...

如果我们只想让我们的片段将其当前标记用作默认值,那么no-op也可以用作片段的参数。

  1. ...
  2. <head th:replace="base :: common_header(_,~{::link})">
  3. <title>Awesome - Main</title>
  4. <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
  5. <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
  6. </head>
  7. ...

看看参数(片段的第一个参数)如何设置为no-op(),这导致片段的这部分不被执行(= no-operation):

  1. <title th:replace="${title}">The awesome application</title>

结果:

  1. ...
  2. <head>
  3. <title>The awesome application</title>
  4. <!-- Common styles and scripts -->
  5. <link rel="stylesheet" type="text/css" media="all" href="/awe/css/awesomeapp.css">
  6. <link rel="shortcut icon" href="/awe/images/favicon.ico">
  7. <script type="text/javascript" src="/awe/sh/scripts/codebase.js"></script>
  8. <link rel="stylesheet" href="/awe/css/bootstrap.min.css">
  9. <link rel="stylesheet" href="/awe/themes/smoothness/jquery-ui.css">
  10. </head>
  11. ...

高级条件插入片段

例如,我们可以这样做,以便仅当用户是管理员时插入我们的片段,并且不插入(emtpy片段)(如果不是)

  1. ...
  2. <div th:insert="${user.isAdmin()} ? ~{common :: adminhead} : ~{}">...</div>
  3. ...

另外,只有满足指定的条件,我们才可以使用无操作令牌来插入片段,但是如果不满足条件,则不需要修改则保留标记:

  1. ...
  2. <div th:insert="${user.isAdmin()} ? ~{common :: adminhead} : _">
  3. Welcome [[${user.name}]], click <a th:href="@{/support}">here</a> for help-desk support.
  4. </div>
  5. ...

另外,如果我们配置了我们的模板解析器来检查模板资源的存在(通过它们的标志),我们可以使用片段本身的存在作为默认操作中的条件:

  1. ...
  2. <!-- The body of the <div> will be used if the "common :: salutation" fragment -->
  3. <!-- does not exist (or is empty). -->
  4. <div th:insert="~{common :: salutation} ?: _">
  5. Welcome [[${user.name}]], click <a th:href="@{/support}">here</a> for help-desk support.
  6. </div>
  7. ...

8.4 拆卸模板片段

  1. <tr class="odd" th:remove="all">
  2. <td>Blue Lettuce</td>
  3. <td>9.55</td>
  4. <td>no</td>
  5. <td>
  6. <span>0</span> comment/s
  7. </td>
  8. </tr>
  1. <a href="/something" th:remove="${condition}? tag : none">Link text not to be removed</a>
  1. <a href="/something" th:remove="${condition}? tag">Link text not to be removed</a>

9 本地变量

  1. <tr th:each="prod : ${prods}">
  2. ...
  3. </tr>
  1. <div th:with="firstPer=${persons[0]}">
  2. <p>
  3. The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
  4. </p>
  5. </div>
  1. <div th:with="firstPer=${persons[0]},secondPer=${persons[1]}">
  2. <p>
  3. The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
  4. </p>
  5. <p>
  6. But the name of the second person is
  7. <span th:text="${secondPer.name}">Marcus Antonius</span>.
  8. </p>
  9. </div>
  1. <div th:with="company=${user.company + ' Co.'},account=${accounts[company]}">...</div>
  1. <p th:with="df=#{date.format}">
  2. Today is: <span th:text="${#calendars.format(today,df)}">13 February 2011</span>
  3. </p>
  1. <p>
  2. Today is:
  3. <span th:with="df=#{date.format}"
  4. th:text="${#calendars.format(today,df)}">13 February 2011</span>
  5. </p>

10 属性优先

  1. <ul>
  2. <li th:each="item : ${items}" th:text="${item.description}">Item description here...</li>
  3. </ul>

同一个标签属性有不同的优先级,级别高的输出

级别 说明 属性
1 片段引入 th:insert th:replace
2 迭代 th:each
3 条件判断 th:if th:unless th:switch th:case
4 局部变量定义 th:object th:with
5 一般属性修改 th:attr th:attrprepend th:attrappend
6 特定属性修改 th:value th:href th:src``...
7 文本(标签体修改) th:text th:utext
8 片段规范 th:fragment
9 片段去除 th:remove

这个优先机制意味着如果属性位置被反转,上述迭代片段将给出完全相同的结果(尽管它的可读性稍差

  1. <ul>
  2. <li th:text="${item.description}" th:each="item : ${items}">Item description here...</li>
  3. </ul>

11 注释和块

11.1 标准的HTML / XML注释

标准的HTML / XML注释可以在Thymeleaf模板的任何地方使用。这些注释中的任何内容都不会被Thymeleaf处理,并将逐字复制到结果中:

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

11.2 Thymeleaf解析器级别的注释块

从模板中简单删除:

  1. <!--/* This code will be removed at Thymeleaf parsing time! */-->

Thymeleaf将删除之间的所有内容,因此,当模板静态打开时,这些注释块也可用于显示代码,因为知道在Thymeleaf处理它时将被删除

  1. <!--/*-->
  2. <div>
  3. you can see me only before Thymeleaf processes me!
  4. </div>
  5. <!--*/-->
  1. <table>
  2. <tr th:each="x : ${xs}">
  3. ...
  4. </tr>
  5. <!--/*-->
  6. <tr>
  7. ...
  8. </tr>
  9. <tr>
  10. ...
  11. </tr>
  12. <!--*/-->
  13. </table>

11.3 Thymeleaf只有原型注释块

当模板静态打开(即作为原型)时,Thymeleaf允许定义标注为注释的特殊注释块,但在执行模板时,Thymeleaf被认为是正常的标记。

  1. <span>hello!</span>
  2. <!--/*/
  3. <div th:text="${...}">
  4. ...
  5. </div>
  6. /*/-->
  7. <span>goodbye!</span>

Thymeleaf的解析系统将简单地删除和标记,而不是其内容,因此将被遗弃。

  1. <span>hello!</span>
  2. <div th:text="${...}">
  3. ...
  4. </div>
  5. <span>goodbye!</span>

与解析器级注释块一样,此功能与方言无关。

11.4 合成th:block标签

th:block仅仅是一个属性的容器,它允许开发人员模板指定哪个属性他们想要的。Thymeleaf将执行这些属性,然后简单地使块,而不是它的内容消失。

因此,它可能是有用的,例如,在创建需要一个以上的迭代表时,<tr>每个元素:

  1. <table>
  2. <th:block th:each="user : ${users}">
  3. <tr>
  4. <td th:text="${user.login}">...</td>
  5. <td th:text="${user.name}">...</td>
  6. </tr>
  7. <tr>
  8. <td colspan="2" th:text="${user.address}">...</td>
  9. </tr>
  10. </th:block>
  11. </table>

尤其是有用的,只有原型的注释块组合使用时:

  1. <table>
  2. <!--/*/ <th:block th:each="user : ${users}"> /*/-->
  3. <tr>
  4. <td th:text="${user.login}">...</td>
  5. <td th:text="${user.name}">...</td>
  6. </tr>
  7. <tr>
  8. <td colspan="2" th:text="${user.address}">...</td>
  9. </tr>
  10. <!--/*/ </th:block> /*/-->
  11. </table>

请注意,此解决方案如何帮助模板是有效的HTML(无需添加禁止<div>内部块<table>),并且仍然工程确定在浏览器中打开时,如静态的原型!

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注