在 Thymeleaf 片段中将数组作为参数传递

问题描述 投票:0回答:4

是否可以将数组传递给这样的片段:

<div th:replace="fragments :: test_fragment( {'one', 'two', 'three'} )"></div>

并像这样迭代片段:

<div th:fragment="test_fragment(numberArray)">

    <span th:each="number : ${numberArray}" th:text="${number}"></span>

</div>

作为奖励,多维数组也可能吗?

我在 Spring Boot 2.0 项目中使用 Thymeleaf。

spring-boot thymeleaf
4个回答
5
投票

是的,这是可能的。下面的代码应该可以解决问题。唯一的区别是在数组外部添加了

${}

<div th:replace="fragments :: test_fragment(${ {'one', 'two', 'three'} })"></div>

3
投票

我找到了两种方法:片段参数和 th:with。

片段参数数组:

<div th:replace="~{fragments :: test_fragment(arrayX = ${ {'a', 'b'} }) }"></div>

Frag参数数组多维:

<div th:replace="~{fragments :: test_fragment(arrayX = ${ {{'a1','a2'},{'b1','b2'}} } ) }"></div>

:带有数组:

<div th:insert="~{fragments :: test_fragment}" th:with="arrayX=${ {'a','b'} }"></div>

th:具有多维数组:

<div th:insert="~{fragments :: test_fragment}" th:with="arrayX=${ {{'a1','a2'},{'b1','b2'}} }"></div>

请注意,当我使用 th:with 时,我使用了 th:insert。这是因为 th:replace 会替换 div 行,从而替换 th:with,这会导致 arrayX 不可用。


0
投票

接受答案的替代方法:

<div th:replace="fragments :: test_fragment('one,two,three')"></div>

并迭代如下:

<div th:fragment="test_fragment(numberArray)">

    <span th:each="number : ${#strings.arraySplit(numberArray, ',')}" th:text="${number}"></span>

</div>

有助于避免某些 IDE 发出警告,这些 IDE 抱怨括号中的 ${} 项中出现逗号 (,)。


0
投票

好吧,这又在我的谷歌帐户下再次发生了,这是一次臭名昭著的垃圾黑客攻击。从上次我经历过这样可疑的事情开始,一位女性向公众展示,有时她看起来不是她自己,欺骗可能出现的东西某物就是某物。[

块引用

]

1.



  1. List item


  1. 列出项目

1

© www.soinside.com 2019 - 2024. All rights reserved.