【问题标题】:how to load thymeleaf fragment into a js variable如何将百里香片段加载到js变量中
【发布时间】:2023-03-06 11:56:01
【问题描述】:

开始在 Spring Boot 中使用 ThymeLeaf,我在将简单片段加载到 JS 变量时遇到问题。尝试向数据表追加一行,其中一个单元格应包含复杂的 HTML 部分。像这样的:

...
var cell_content = <Load thymeleaf fragment content with parameters>;
...

现在假设我有一个名为:“x :: docs-popup”的 ThymeLeaf 片段,其中包括一个用于文档操作的 Bootstrap 弹出窗口,我如何加载此弹出窗口的内容,包括将参数传递到 javascript 变量 cell_content 中,所以我将它附加到生成的行。

换句话说,如果我使用 php,我会执行以下操作:

 var cell_content = '<?php echo fragment_loader($document_object); ?>'

【问题讨论】:

    标签: javascript spring-boot fragment thymeleaf


    【解决方案1】:

    有趣的问题...在 thymleaf 3 中,这样的事情对我有用:

    <script th:inline="javascript">
        cell_content = '[# th:insert="~{x :: docs-popup}"/]';
    </script>
    

    但是,它不会自动转义包含中的任何内容。所以杂散的单引号会破坏javascript。

    我可能会在默认情况下将其正常包含在页面上(但将其设为display: hidden)并仅通过 id 引用它。

    【讨论】:

    • 不幸的是,您的解决方案对我不起作用,console.log(cell_content);显示确切分配的字符串并且不加载片段!你知道为什么吗?将标签添加为隐藏对我的情况来说并不实用,因为我有一个数据表,页面中可能有很多记录。
    • 您使用的是百里香叶 3 吗?我不确定这种语法是否适用于 thymeleaf 2。
    • 不幸的是,我使用的是 Thymeleaf 2.1.5。有什么解决方法吗?!
    【解决方案2】:

    一种直接的方法是调用一个返回片段 html 的控制器。请参阅文档in the section about Fragment inclusion from Spring @Controller

    // in your view
    <script th:inline="javascript">
    /*<![CDATA[*/ 
       var url = /*[[@{/docs/}]]*/;
       $.get(url + param, function(fragment) {
              $rowDocPopup = $('...'); // get selector for the cell you need
              $rowDocPopup.replaceWith(fragment);
        });
    /*]]>*/
    </script>
    

    然后在控制器中:

    @RequestMapping("/docs/{id}")
    public String reloadDocsPopup(@PathVariable Long id, Model model){
        // do stuff and put parameter data in model 
        return "templates/x :: docs-popup";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      • 2017-07-31
      • 2012-09-21
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多