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

Viewed 377

Using Thymeleaf th:each loop, whitespace is removed (or can't be added).

Thymeleaf code:

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

I expected:

<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>

but html rendered below.

<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>

How to add whitespace (in html file new line) using Thymeleaf th:each?

My Thymeleaf version is 3.0.12.RELEASE

1 Answers

If you want the links to be arranged horizontally with a single white space between them (as opposed to arranging them vertically using display:block) then you can use the Thymeleaf synthetic <th:block> element (documented here):

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

This will give you the same layout as you show in your question, when you run the first code snippet.


Update:

You can also use <span> instead of <th:block>, if you prefer:

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

This will give you the same end result (links arranged horizontally with a space between them), but the HTML generated to produce this layout will, of course, be slightly different.

Related