在thymeleaf中包含JavaScript变量

Dee*_*ass 15 html java spring web thymeleaf

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

尝试:

<div th:if="${myVariable == 5}">
 //some code
</div>
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

geo*_*and 33

你想要做的事情是行不通的,因为Thymeleaf在服务器端处理模板,因此它可以访问的变量是在它的模型中定义的变量.

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

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

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

    ...
/*]]>*/
</script>
Run Code Online (Sandbox Code Playgroud)

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

有关模式的详细信息,请查看文档的这一部分.