th:style isn't working in my project depending on case true:false

44 Views Asked by At

My text have to change color depending on true:false case using Thymeleaf, but whatever I did it doesn't work.

    <table th:each="book : ${assignedBooks}">
        <tr th:style="${book.getExpired()? 'color: red;' : 'color: blue;'}" th:text="${book.getName() + ', ' + book.getAuthor() + ', ' + book.getYear()}">'someBook'</tr>
    </table>

I have checked .getExpired == true, but I don't understand why it still doesn't work.

2

There are 2 best solutions below

0
andrewJames On

Your <table> HTML contains one or more <tr> rows - but those rows do not contain any <td> cells. Place the text (from th:text="...") inside a <td>.

<table th:each="book : ${assignedBooks}">
    <tr th:style="${book.getExpired()? 'color: red;' : 'color: blue;'}">
        <td th:text="${book.getName() + ', ' + book.getAuthor() + ', ' + book.getYear()}">'someBook'</td>
    </tr>
</table>

You can troubleshoot problems like this for yourself by looking at the HTML which is produced by Thymeleaf - and which is displayed in your browser. Remember: Thymeleaf generates HTML on the server, and then sends that HTML to the browser. So you can see exactly what Thymeleaf produced (unless it throws an error/exception on the server).

Usually there is a "View Source" menu item in your browser (depending on which browser you are using).

In your case, using the approach in your question, you will probably see something like the following:

The Adventures of Tom Sawyer, Mark Twain, 1876
<table>
    <tbody>
        <tr style="color: red;"></tr>
    </tbody>
</table>

See how the lack of any <td> cells causes the text to be rendered outside of the table. It's up to each browser how it attempts to render incomplete/invalid HTML - so you may see something similar but different.


See table for more details on how to create a valid/complete HTML table.

0
Paul Tofunmi On

This is a revised version of your codebase and should work.

I will explain the changes I carried out.

<table th:each="book : ${assignedBooks}">
    <tr th:style="${book.expired} ? 'color: red;' : 'color: blue;'"> 
        <td th:text="${book.name + ', ' + book.author + ', ' + book.year}">someBook</td>
    </tr>
</table>
  • I've shortened book.getExpired() to book.expired. Thymeleaf can directly interpret boolean properties.
  • Removed Quotes: I've removed the quotes around 'someBook'. Thymeleaf treats content within the or as text to be displayed.

Additional Tips:

  • Debugging: Add temporary th:text elements within your table row to output the values of book.name, book.author, etc., to ensure the data is being fetched properly.
  • Verify book.expired: Double-check that your book.expired property is indeed returning a boolean (true or false) as expected. You can temporarily add a th:text="${book.expired}" somewhere inside the element to check.