是否可以将数组传递给这样的片段:
<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。
是的,这是可能的。下面的代码应该可以解决问题。唯一的区别是在数组外部添加了
${}
。
<div th:replace="fragments :: test_fragment(${ {'one', 'two', 'three'} })"></div>
我找到了两种方法:片段参数和 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 不可用。
接受答案的替代方法:
<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 抱怨括号中的 ${} 项中出现逗号 (,)。