我正在尝试将一个值传递给我的 javascript 函数,但该函数调用取决于一个 bool 变量。在我最近升级到 thymeleaf security 5 之前,我的工作一直很好。
这是代码片段。
<body th:onload="${timerEnabled} ? 'javascript:runTimer(\'' + ${timeRemaining} + '\');'">
timerEnabled 必须为真才能完成函数调用,但 thymeleaf 现在抛出异常
org.thymeleaf.exceptions.TemplateProcessingException: Only variable expressions returning numbers or booleans are allowed in this context, any other datatypes are not trusted in the context of this expression, including Strings or any other object that could be rendered as a text literal. A typical case is HTML attributes for event handlers (e.g. "onload"), in which textual data from variables should better be output to "data-*" attributes and then read from the event handler.
我该如何解决这个问题?谢谢。
最佳答案
从 Thymeleaf 3.0.10 开始,他们修复了一个关于未转义代码的安全漏洞。
尝试
<body th:onload="[[${timerEnabled}]] ? 'javascript:runTimer(\'' +
[[${timeRemaining}]] + '\');'">
或者推荐的方式:
<body th:data1="${timerEnabled}"
th:data2="${timeRemaining}"
th:onload="this.getAttribute('data1') ? javascript:runTimer(this.getAttribute('data2'));">
阅读更多:https://github.com/thymeleaf/thymeleaf/issues/707 和: http://forum.thymeleaf.org/Thymeleaf-3-0-10-JUST-PUBLISHED-tt4031348.html#a4031353
关于javascript - 在此上下文中只允许返回数字或 bool 值的变量表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52933002/