0

I just wanted to have different colors for the different enum values in my DataTable. I also need th:text for my filter I created.

What can I do so that I can use th:text and keep my span formatting?

<td class="incident" th:text="${ticket.getStatus().toString()}">
    <a th:if="${ticket.getStatus().toString()} == 'OPEN'">
        <span th:text="${ticket.getStatus().toString()}" class="badge text-white" style="background-color: #F93154"></span>
    </a>
    <a th:if="${ticket.getStatus().toString()} == 'IN_PROCESS'">
        <span th:text="${ticket.getStatus().toString()}" class="badge text-white" style="background-color: #FFEA00"></span>
    </a>
    <a th:if="${ticket.getStatus().toString()} == 'CLOSED'">
        <span th:text="${ticket.getStatus().toString()}" class="badge text-white" style="background-color: #00E676"></span>
    </a>
</td>
andrewJames
  • 19,570
  • 8
  • 19
  • 51
Dana
  • 11
  • 1

1 Answers1

0

Change this:

<td class="incident" th:text="${ticket.getStatus().toString()}">

to this:

<td class="incident">

The reason is that the th:text expression in the <td> tag will cause all child content to be ignored.


You can also clean up the Thymeleaf a bit by changing getStatus() to just status, since Thymeleaf will automatically apply JavaBean naming rules to the field name status and acutally invoke getStatus() behind the scenes.


I would also recommend considering updating your enum, so that it can return string values directly - see Using Enum values as String literals. This will further allow you to simplify your Thymeleaf, and get rid of all those .toString() methods embedded in the template.

For example, assume you have the enum:

public enum Status {
    OPEN, IN_PROCESS, CLOSED;
}

You can change that to the following:

public enum Status {
    OPEN("Open"),
    IN_PROCESS("In Process"),
    CLOSED("Closed");

    private final String label;

    private Status(String s) {
        label = s;
    }
    
    public String getLabel() {
        return label;
    }
    
    // toString and comparison methods not shown
}

Now each enum has a related string value (the "label") which you can use as follows:

<table>
    <td class="incident">
        <a th:if="${ticket.status.label} == 'Open'">
            <span th:text="${ticket.status.label}" 
                  class="badge text-white" 
                  style="background-color: #F93154"></span>
        </a>
        <a th:if="${ticket.status.label} == 'In Progress'">
            <span th:text="${ticket.status.label}" 
                  class="badge text-white" 
                  style="background-color: #FFEA00"></span>
        </a>
        <a th:if="${ticket.status.label} == 'Closed'">
            <span th:text="${ticket.status.label}" 
                  class="badge text-white" 
                  style="background-color: #00E676"></span>
        </a>
    </td>
</table>
andrewJames
  • 19,570
  • 8
  • 19
  • 51