lr_optim
lr_optim

Reputation: 381

How to display something on Thymeleaf table if not null

I have a table:

<table>
 <thead>
   <tr>
    <th>Header1</th>
    <th>Header2</th>
   </tr>
 </thead>
 <tbody>
  <div th:if="${param1 != null}">
    <td class="dripicons-checkmark"></td>
  </div>
  <div th:if="${param2 != null}">
    <td class="dripicons-checkmark"></td>
  </div>
 </tbody>
</table>

param1 and param2 are coming from my controller:

model.addAttribute("param1", param1)
model.addAttribute("param2", param2)

...and they can be null or contain some info. I'm trying to show a checkmark under correct header. If param1 is not null, I want to show the checkmark under Header1 and if param2 is not null, I want to show the checkmark under Header2 and so on. The code above shows the checkmark always under Header1, if either one of the params are not null. How can I put the icon under a correct header?

Upvotes: 0

Views: 828

Answers (1)

andrewJames
andrewJames

Reputation: 21910

If either one of your params is null, then you will only be creating one <td> cell in the <tr> row. Your table always needs two cells to match the two headings you have.

There are various ways around this. The following is one way, which I think is reasonably concise:

<tbody>
    <td th:class="${param1} != null ? 'dripicons-checkmark' : null"></td>
    <td th:class="${param2} != null ? 'dripicons-checkmark' : null"></td>
</tbody>

In this example, we always have two row cells.

The "if" condition is inside a th:class attribute, so there is no need for any surrounding <div> elements.

The HTML generated by this is as follows, when the first value is null, but the second value is not null:

<table>
    <thead>
        <tr>
            <th>Header1</th>
            <th>Header2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td class="dripicons-checkmark"></td>
        </tr>
    </tbody>
</table>

Upvotes: 1

Related Questions