当前位置 博文首页 > 文章内容

    Thymeleaf 与 Javascript

    作者: 栏目:未分类 时间:2020-08-22 9:00:56

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



     

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