Thymeleaf:列表的逗号分隔值?

Jac*_*ack 1 html java spring thymeleaf

我是 Thymeleaf 的初学者,我有一个列表,想要通过逗号分隔来列出一行中的元素,例如 London、Paris、Berlin、HonKong(最后一个元素之后不会有逗号)。但是,以下代码会生成新行。那么,我怎样才能让它按照上面的解释工作呢?

<td th:each="city : ${country.cityList}">
    <td th:text="${city.name}? ${city.name} + ',' : ${city.name}"></td>
</td>

Run Code Online (Sandbox Code Playgroud)

我知道它还在最后一个元素的末尾添加了一个额外的逗号,我需要使用索引来检测最后一个索引。我怎样才能做到这一点?

and*_*mes 7

您可以使用一系列<span>标签来保存文本。

\n

您可以使用 Thymeleaf 的迭代状态跟踪值来了解何时处理列表中的最后一项。

\n

结合这些:

\n
<td>\n    <span th:each="city,iterStat : ${country.cityList}"\n          th:text="${city.name} + ${!iterStat.last ? \', \' : \'\'}"></span>\n</td>\n
Run Code Online (Sandbox Code Playgroud)\n

iterStat.last值是一个布尔值,它告诉我们何时处理最终值 - 并且!(非)运算符用于抑制最后的逗号+空格。

\n
\n

更新

\n

根据评论:

\n
\n

如何为 city.name 制作 href 链接,但只为逗号制作 span ?

\n
\n

对于这样的事情,您可以将th:each表达式移动到父标记中 - 这可能<th:block>很有用,因为它本身不会生成任何 HTML:

\n
<th:block th:each="city,iterStat : ${country.cityList}">\n    <a th:text="${city}" th:href="${city}"></a><span th:text="${!iterStat.last ? \', \' : \'\'}"></span>\n</th:block>\n
Run Code Online (Sandbox Code Playgroud)\n

在内部,<th:block>...</th:block>您可以使用多个子标签来构建您需要的任何内容。

\n

使用上面的 Thymeleaf,最终结果可能是以下 HTML:

\n
<a href="S\xc3\xa3o Paulo">S\xc3\xa3o Paulo</a><span>, </span>\n<a href="Rio de Janeiro">Rio de Janeiro</a><span>, </span>\n<a href="Brasilia">Brasilia</a><span></span>\n
Run Code Online (Sandbox Code Playgroud)\n

<span></span>这会在末尾生成一个空。

\n

如果您不想要那个空范围,您可以通过使用显式th:if表达式来增强逻辑:

\n
<th:block th:each="city,iterStat : ${country.cityList}">\n    <a th:text="${city}" th:href="${city}"></a><span th:if="${!iterStat.last}">, </span>\n</th:block>\n
Run Code Online (Sandbox Code Playgroud)\n

现在,你会得到这样的东西:

\n
<a href="S\xc3\xa3o Paulo">S\xc3\xa3o Paulo</a><span>, </span>\n<a href="Rio de Janeiro">Rio de Janeiro</a><span>, </span>\n<a href="Brasilia">Brasilia</a>\n
Run Code Online (Sandbox Code Playgroud)\n

现在,末尾没有空的跨度。

\n


Sla*_*nov 6

您应该查看 Thymeleaf#strings实用方法。有一组函数可用于拆分和连接不同类型的列表。你的代码可能看起来像......

<td th:text="${#strings.listJoin(country.cityList.![name], ',')}"></td>
Run Code Online (Sandbox Code Playgroud)