thymeleaf - 脚本和 th:block [英] thymeleaf - script and th:block

查看:134
本文介绍了thymeleaf - 脚本和 th:block的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

)有没有办法在script"标签中使用th:block"标签?类似的东西:

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

推荐答案

我们有要求插入一个外部 javascript(里面有 thymleaf 变量)并将其包装在 cdata 中,它基于@Pau 的解决方案:

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.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining)
  • Multiline comment CDATA notation, so that minimized code without linewraps will not be parsed as a comment only (https://en.wikipedia.org/wiki/CDATA#Use_of_CDATA_in_program_output)
  • Textual prototype-only comment blocks adding code, to prevent rendering the content in static files and prevent the IDE from being confused by invalid code. (https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#textual-prototype-only-comment-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.org/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.org/doc/tutorials/3.0/usingthymeleaf.html)
  • Finally the fragment specific syntax, to include a template via template path (https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#fragment-specification-syntax)

这篇关于thymeleaf - 脚本和 th:block的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆