在 thymeleaf 中包含 JavaScript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22575136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:36:11  来源:igfitidea点击:

Including JavaScript variable inside thymeleaf

javahtmlspringwebthymeleaf

提问by Deepak Ramakrishnan Kalidass

How do I include a JavaScript variable inside thymeleaf for checking a condition?

如何在 thymeleaf 中包含一个 JavaScript 变量来检查条件?

Tried:

尝试:

<div th:if="${myVariable == 5}">
 //some code
</div>

but it's not working.

但它不起作用。

回答by geoand

What you are trying to do won't work, since Thymeleaf processes the template on the server side and therefore the variables it has access to are the ones defined in it's model.

您尝试执行的操作是行不通的,因为 Thymeleaf 在服务器端处理模板,因此它可以访问的变量是在其模型中定义的变量。

If you had myVariablein the model on which Thymeleaf is operating, it would work. If what you want is to set the value of a Javascript variable in a Thymeleaf template, you can do the following:

如果您myVariable在 Thymeleaf 运行的模型中使用它,它将起作用。如果您想要在 Thymeleaf 模板中设置 Javascript 变量的值,您可以执行以下操作:

<script th:inline="javascript">
/*<![CDATA[*/
    ...

    var myVariable= /*[[${myVariable}]]*/ 'value';

    ...
/*]]>*/
</script>

Inside the script you could have any logic you want including hide/show etc.

在脚本中,您可以拥有任何您想要的逻辑,包括隐藏/显示等。

Check out thispart of the documentation for mode details.

查看文档的这一部分以了解模式详细信息。

回答by Saurabh

<script>
   // <![CDATA[
     ...Your script, here
   // ]]>
</script>

回答by Taugenichts

With thymeleaf 3, the CDATA block had to be removed to reference my variable inline or the parser ignored it completely. This syntax worked successfully for me post upgrade:

对于 thymeleaf 3,必须删除 CDATA 块以引用我的内联变量,否则解析器会完全忽略它。升级后,此语法对我来说很成功:

<script th:inline="javascript">
     var myVariable = [[${#vars.myVar}]];
     ...
</script>

Note: if you also referenced your variables as [[${#ctx.variables.myVar}]], it will no longer work in thymeleaf 3 as ctx no longer has a variable named variables.

注意:如果您还将变量引用为 [[${#ctx.variables.myVar}]],它将不再适用于 thymeleaf 3,因为 ctx 不再有名为 variables 的变量。