是否可以将数组传递给这样的片段:
<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项目中使用Thymelaf。
是的,这是可能的。下面的代码应该可以完成任务。唯一的区别是在数组之外添加了${}
。
<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>
th:带阵列:
<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发出警告,这些警告抱怨括号内的${}项中出现逗号(,(。