posts - 15,  comments - 1,  views - 41372
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

在 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());  

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

posted on   jinweijie0527  阅读(37416)  评论(1编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· Apache Tomcat RCE漏洞复现(CVE-2025-24813)
点击右上角即可分享
微信分享提示