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
2 Answers
Reset to default 5You 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
版权声明:本文标题:javascript - thymeleaf - script and th:block - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744555603a2612453.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论