简体   繁体   English

如何将百里香片段加载到js变量中

[英]how to load thymeleaf fragment into a js variable

Started using ThymeLeaf with Spring Boot, and I am facing an issue in loading a simple fragment into a JS variable. 开始在Spring Boot中使用ThymeLeaf,在将简单片段加载到JS变量中时遇到一个问题。 Trying to append a row to a data table, where one of the cells should include a complex HTML portion. 尝试在数据表中追加一行,其中一个单元格应包含复杂的HTML部分。 Something like this: 像这样:

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

Now supposing that I have a ThymeLeaf fragment called: "x :: docs-popup" which includes a Bootstrap Popup for documents manipulation, How can I load the content of this popup, including passed parameters into the javascript variable cell_content, so that I append it to the generated row. 现在假设我有一个ThymeLeaf片段,名为:“ x :: docs-popup”,其中包括用于文档操作的Bootstrap弹出窗口,我如何加载该弹出窗口的内容,包括将参数传递到javascript变量cell_content中,以便附加它到生成的行。

In other words, If I am using php, I would do the following: 换句话说,如果我使用的是php,我将执行以下操作:

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

Interesting question... in thymleaf 3, something like this works for me: 有趣的问题...在胸腺3中,类似以下内容对我有用:

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

However, it doesn't automatically escape anything in the include. 但是,它不会自动转义包含中的任何内容。 So stray single quotes will break the javascript. 因此,流浪单引号将破坏javascript。

I would probably include it normally on the page (but make it display: hidden ) by default and just refer to it by id. 我可能会默认将其正常包含在页面上(但默认情况下将其display: hidden ),并仅通过id进行引用即可。

One straightforward way is to issue a call to a controller that returns the html of the fragment. 一种简单的方法是发出对返回片段html的控制器的调用。 See the doc in the section about Fragment inclusion from Spring @Controller 请参阅有关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>

Then in the controller: 然后在控制器中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM