问题
项目使用springboot整合Thymeleaf在页面定义数组时遇到问题,数组格式为
var d = [[123456,2],[156449,3]]
运行后控制台报错
org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "1262304000000, 6], [1264982400000, 3057], [1267401600000, 20434], [1270080000000, 31982], [1272672000000, 26602], [1275350400000, 27826], [1277942400000, 24302], [1280620800000, 24237], [1283299200000, 21004], [1285891200000, 12144], [1288569600000, 10577], [1291161600000, 10295" (template: "/ui/widgets" - line 564, col 24)
原因
Thymeleaf中的内联表达式允许直接在 HTML 文本中使用标准表达式,
[[]]
相当于th:text
,对含有 HTML 标签的内容自动进行字符转义。
根据控制台打印的日志可以看出, Thymeleaf把"[["和"]]"之间的内容直接转化展示,所以报错无法解析表达式
解决方法
Thymeleaf的th:inline
值 | 描述 |
---|---|
none | 禁止内联表达式,可以原样输出 [[]] 和 [()] 字符串 |
text | 文本内联,可以使用 th:each 等高级语法 |
css | 样式内联,如:<style th:inline="css"> |
javascript | 脚本内联,如:<style th:inline="javascript"> |
none
<!-- [[1, 2], [3, 4]] -->
<p th:inline="none">[[1, 2], [3, 4]]</p>
<script th:inline="none">
var d = [[1, 2], [3, 4]];
</script>
text
<!-- 北京 上海 广州 深圳 -->
<p th:inline="text">
[# th:each="city : ${cities}"]
[(${city.name})]
[/]
</p>
css
<style th:inline="css">
body {
background-color:[[${bgColor}]];
}
</style>
javascript
<script th:inline="javascript">
var user = [[${user}]];
alert("用户名:" + user.name);
</script>
使用none,即在标签中加入th:inline="none"
thymeleaf参考资料:https://fanlychie.github.io/post/thymeleaf.html