admin管理员组

文章数量:1389204

) Is there any way to use "th:block" tag inside "script" tag? something like that:

<script type="text/javascript">
    <th:block>
        var test = 1;
    </th:block>
</script>

) Is there any way to use "th:block" tag inside "script" tag? something like that:

<script type="text/javascript">
    <th:block>
        var test = 1;
    </th:block>
</script>
Share Improve this question asked Apr 28, 2017 at 7:49 WEBCENTERWEBCENTER 1434 silver badges15 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

You should use the attribute th:inline="javascript", then you can use a th:block but not in a tag, you must use a syntax like next:

<script th:inline="javascript">
    [#th:block th:each="item : ${items}"]
      - [#th:block th:utext="${item}" /]
    [/th:block]
</script>

We had the requirements to insert an external javascript (with thymleaf variables inside) and wrap it in cdata, it's based on @Pau's solution:

<script th:inline="javascript">
  /*<![CDATA[*/
  /*[+ [# th:insert="~{path/to/file.js}" /] +]*/
  /*]]>*/
</script>

In these five lines we packed:

  • Javascript inlining, to trigger thymeleaf parsing of the content (https://www.thymeleaf/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining)
  • Multiline ment CDATA notation, so that minimized code without linewraps will not be parsed as a ment only (https://en.wikipedia/wiki/CDATA#Use_of_CDATA_in_program_output)
  • Textual prototype-only ment blocks adding code, to prevent rendering the content in static files and prevent the IDE from being confused by invalid code. (https://www.thymeleaf/doc/tutorials/3.0/usingthymeleaf.html#textual-prototype-only-ment-blocks-adding-code)
  • Natural javascript templates, to use thymeleaf inside javascript, we used the empty tag approach and we omit th:block here, because it is the default (https://www.thymeleaf/doc/tutorials/3.0/usingthymeleaf.html#natural-javascript-and-css-templates)
  • Inserting of fragments with th:insert to insert a transpiled/minified external javascript with thymeleaf variables included. You can use th:text or th:utext too, but these insert the content of the external javascript without parsing it, so in our case the variables wouldn't have been resolved. (https://www.thymeleaf/doc/tutorials/3.0/usingthymeleaf.html)
  • Finally the fragment specific syntax, to include a template via template path (https://www.thymeleaf/doc/tutorials/3.0/usingthymeleaf.html#fragment-specification-syntax)

本文标签: javascriptthymeleafscript and thblockStack Overflow