概述

个别状况下只可能从Controller传一个数组或者List的变量到HTML来遍历,然而也有场景是须要间接在HTML上定义变量,但发现Thymeleaf这么简略的办法都没有,找了内置的arrayslists都没有方法定义数组,最初找到了strings有一个办法strings.arraySplit,能够用一个字符串截取逗号,来解决动态数组的定义。

例子

间接遍历渲染

<li th:each="fruit : ${#strings.arraySplit('苹果,西瓜,榴莲',',')}" th:text="${fruit}"></li>

定义变量并渲染

<div th:with="fruits=${#strings.arraySplit('苹果,西瓜,榴莲,凤梨',',')}">   <li th:each="fruit : ${fruits}" th:text="${fruit}"></li></div>

另外一种办法

截取字符串的办法如同有点不太好看,也有另外一种办法,能够重写Thymeleaf的 org.thymeleaf.expression.Arrays 类,减少一个“脱裤子放屁”的办法。

public Object[] asList(Object[] objects) {   return objects;}

HTML上应用

<ul>    <li th:each="fruit : ${#arrays.asList('苹果,西瓜,榴莲')}" th:text="${fruit}"></li></ul>