【问题标题】:Including JavaScript variable inside thymeleaf在 thymeleaf 中包含 JavaScript 变量
【发布时间】:2014-04-29 18:53:21
【问题描述】:

如何在 thymeleaf 中包含 JavaScript 变量以检查条件?

试过了:

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

但它不起作用。

【问题讨论】:

    标签: java html spring web thymeleaf


    【解决方案1】:

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

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

    <script th:inline="javascript">
    /*<![CDATA[*/
        ...
    
        var myVariable= /*[[${myVariable}]]*/ 'value';
    
        ...
    /*]]>*/
    </script>
    

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:
        <script>
           // <![CDATA[
             ...Your script, here
           // ]]>
        </script>
        

        【讨论】:

          猜你喜欢
          • 2013-10-05
          • 1970-01-01
          • 2016-03-17
          • 2018-11-20
          • 2023-03-21
          • 1970-01-01
          • 1970-01-01
          • 2015-01-19
          • 1970-01-01
          相关资源
          最近更新 更多