如何使用 Thymeleaf 的 th:each 为内联 dom 保留空格?

How to keep whitespace using Thymeleaf's th:each for inline dom?

使用 Thymeleaf th:each 循环,删除空格(或无法添加)。

Thymeleaf 代码:

<div>
  <a href="#" style="text-decoration: underline" th:each="for loop here"></a>
</div> 

我预计:

<div>
  <a href="#" style="text-decoration: underline">Link 1</a>
  <a href="#" style="text-decoration: underline">Link 2</a>
  <a href="#" style="text-decoration: underline">Link 3</a>
  <a href="#" style="text-decoration: underline">Link 4</a>
  <a href="#" style="text-decoration: underline">Link 5</a>
</div>

但 html 渲染如下。

<div><a href="#" style="text-decoration: underline">Link 1</a><a href="#" style="text-decoration: underline">Link 2</a><a href="#" style="text-decoration: underline">Link 3</a><a href="#" style="text-decoration: underline">Link 4</a><a href="#" style="text-decoration: underline">Link 5</a></div>

如何使用 Thymeleaf th:each 添加空格(在 html 文件新行中)?

我的 Thymeleaf 版本是 3.0.12.RELEASE

如果您希望链接水平排列,中间有一个白色 space(而不是使用 display:block 垂直排列),那么您可以使用 Thymeleaf 合成器 <th:block> 元素(记录 here):

<div>
    <th:block th:each="item : ${items}">
        <a href="#" th:text="${item}" style="text-decoration: underline;"></a>
    </th:block>
</div>

当您 运行 第一个代码片段时,这将为您提供与您在问题中显示的布局相同的布局。


更新:

您也可以使用 <span> 代替 <th:block>,如果您愿意:

<div>
    <span th:each="item : ${items}">
        <a href="#" th:text="${item}" style="text-decoration: underline;"></a>
    </span>
</div>

这将为您提供相同的最终结果(水平排列的链接之间有 space),但是为生成此布局而生成的 HTML 当然会略有不同。