关于thymeleaf:Thymeleaf-在HTML定义数组常量并遍历

26次阅读

共计 628 个字符,预计需要花费 2 分钟才能阅读完成。

概述

个别状况下只可能从 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>

正文完
 0