thymeleaf毕竟是一个脚本语言,在生成html时有一些特殊的字符串需要通过特定的拼接才能完成,本文主要介绍下在thymeleaf下字符串的常用操作
字符串拼接
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
<span th:text="|Welcome to our application, ${user.name}!|">
<span th:text="${onevar} + ' ' + |${twovar}, ${threevar}|">
url地址拼接
<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3&name=asd' (plus rewriting) -->
<a href="details.html"
th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id},name=${o.name})}">view</a>
<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/user/3/details?name=123&type=1' (plus rewriting) -->
<a href="details.html" th:href="@{/user/{id}/details(id=${user.id},name=${user.name},type=${user.userType})}">view</a>
<!-- /details/123?orderId=1 -->
<a th:href="@{'/details/'+${user.login}(orderId=${o.id})}">view</a>
判断
<span th:text="*{age}?: '(no age specified)'">27</span
<span th:text="*{age != null}? *{age} : '(no age specified)'">27</span>
以前两种是等价的 ?:表示在不等于null的情况下,输出值为判断条件,否则为定义的默认值
具体参考上篇文章
- If-then: (if) ? (then)
- If-then-else: (if) ? (then) : (else)
- Default: (value) ?: (defaultvalue)
appending 和prepending
<input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" />
<!-- If you process this template with the cssStyle variable set to "warning" , you will get: -->
<input type="button" value="Do it!" class="btn warning" />
<tr th:each="prod : ${prods}" class="row" th:classappend="${prodStat.odd}? 'odd'">
th:remove
当html作为模板使用时,会根据模板中定义的变量等等来生成html页面,但是如果直接作为静态页面来查看,他的显示效果并不好,所以出现了th:remove的标签
例如:
<table> <tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
<th>COMMENTS</t