Thymeleaf在js中拼接一段字符串或者一段html代码

编程知识 行业动态 更新时间:2024-06-13 00:22:28

在 javascript 代码中使用 Thymeleaf 模板引擎:

<script th:inline="javascript"> $("#content").html( "<select name='status'>"+ " <option value=''>[[#{adminmon.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="#{adminmon.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());  

text/csstext/html 和 text/javascript 等属性值规定脚本的 MIME 类型,它表示浏览器的解释方式,例如,text/javascript 告诉浏览器按照 Javascript 来解析执行。


原文:点击打开链接

更多推荐

Thymeleaf在js中拼接一段字符串或者一段html代码

本文发布于:2023-04-02 13:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/345809a1a326eee2ce8b158e1248587f.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   代码   Thymeleaf   js   html

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!