[英]Thymeleaf - Iterating over a model attribute inside Javascript code
我正在尝试编写一些需要使用模型属性的 Javascript 代码。 这是我定义脚本标签的方式:
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
//need some loops
/*]]>*/
</script>
我需要做的是,使用脚本内模型属性的each
迭代。 到目前为止,我无法用th:each
做到这一点。 任何帮助表示赞赏。
我想您需要将模型 attrubite 包裹在双括号中,如下所示: [[${modelAttribute}]]
。 Thymeleaf 文档的脚本内联部分可以提供一些帮助: http : //www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
var theList = [[${modelAttribute}]]
for (i = 0; i < theList.length; i++) {
doSomething(theList[i]);
}
/*]]>*/
</script>
你也可以这样做,我猜这是最紧凑的:
在您的@Controller
:
model.addAttribute("items", new String[] { "item1", "item2", "item3" });
在您的模板中:
<script type="text/javascript" th:inline="javascript">
var items = [];
/*[# th:each="n : ${items}"]*/
items.push("[(${n})]");
/*[/]*/
</script>
此处解释了其他有用的内容: [MAJOR FEAT] 文本模板模式的新语法 #395
Thymeleaf 3 -> 见 yglodt 答案
如果您坚持使用Thymeleaf 2并且您的模型属性很复杂(例如 Maxime Laval 的情况),我最终会遍历脚本:
<script th:inline="javascript">
var dataLayer = [];
</script>
<script th:each="item:${items}" th:inline="javascript">
dataLayer.push({'attr1':item.attr1, 'attr2':item.attr2, 'attr3':item.attr3});
</script>
<script th:inline="javascript">
console.log(dataLayer); // do whatever you want with dataLayer...
</script>
不是很好,但我找不到更好的谷歌分析。
通过添加/*[[${name}]]*/
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
var theList = /*[[${modelAttribute}]]*/
for (i = 0; i < theList.length; i++) {
doSomething(theList[i]);
}
/*]]>*/
</script>
如果您坚持使用 Thymeleaf 2,另一种方法是在您的 Script-Tag 中滥用“th:block”-Element
<script type="text/javascript">
var arrayOfIds= [
<th:block th:each="element: ${list}" th:inline="text">[[${element.Id}]],</th:block>
-1
];
arrayOfIds.pop(); // Remove the superflous last Element
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.