简体   繁体   中英

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. Trying to append a row to a data table, where one of the cells should include a complex HTML portion. 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.

In other words, If I am using php, I would do the following:

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

Interesting question... in thymleaf 3, something like this works for me:

<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.

I would probably include it normally on the page (but make it display: hidden ) by default and just refer to it by id.

One straightforward way is to issue a call to a controller that returns the html of the fragment. See the doc 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>

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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