在 javascript 代碼中使用 Thymeleaf 模板引擎:
<script th:inline="javascript"> $("#content").html( "<select name='status'>"+ " <option value=''>[[#{admin.common.choose}]]</option>"+ " <option value="+[[${status}]]+">[[#{'Order.Status.' + ${value}}]]</option>"+ "</select>"); </script>
script
標簽中的 th:inline="javascript"
屬性值表示可以使用內聯 js ,即可以在 js 代碼中使用 [[]]
取值:
var user = [[${user}]];
以上是在 Javascript 代碼中使用 Thymeleaf 模板引擎的簡單示例,但有時也會遇到不可解決或者說很難解決的問題。例如,如果要在 js 代碼中輸出一個段 html 代碼,並且要在 html 代碼中作循環操作,而 html 本身並沒有提供這種功能的實現,這時要使用 Thymeleaf 的 th:each
屬性,但是如何使用 th:each
在 js 中實現? 這時就不能像上面那樣的使用字符串拼接內聯 js 來實現了,因為 th:xx
是要作為標簽的屬性放在標簽內部的,js 解析不了。解決的方案是將 html 代碼放在一個使用 text/html
解析的 script
標簽中,這樣就會使用 html 的解析方式來解析這些代碼,示例如下:
<script type="text/html" id="thymeleafTable"> <table> <tr> <th th:text="#{Order.type}"></th> <td> <select name="type"> <option value="" th:text="#{admin.common.choose}"></option> <option th:each="value : ${types}" th:value="${value}" th:attr="selected = ${value == type} ? 'selected' : ''" th:text="#{'Order.Type.' + ${value}}"></option> </select> </td> </tr> </table> </script>
然后在 js 代碼中使用腳本的 id 來調用該腳本:
$("#content").html($("#thymeleafTable").html());