Search code examples
javahtmlcssthymeleaf

Thymeleaf: how to make table with different colors


Could somebody say how to make table with different colors using Thymeleaf? I have a list of events with integer value of risk weight. And I need to colorize the html column (choose class) by condition. If risk less then 20 is green, if risk from 20 to 50 if yellow, if risk more then 50 is red. How to do several condtions for one ? My variant is not working.

<td th:text="${data.riskIndex}" th:if="${data.riskIndex &lt; 20 and data.riskIndex &gt;= 0}" class="green"></td>

Solution

  • In that case I would use the th:class instead of th:if (or th:classappend if every column shares some additional classes). Inside the th:class I would provide a double Elvis operator (unfortunately) to check condition.

    <td th:text="${data.riskIndex}" th:class="${data.riskIndex lt 20} ? 'green' : (${data.riskIndex le 50} ? 'yellow' : 'red')"></td>
    

    Alternatively, when there would be more conditions and you would like not to involve javascript, you can provide some utility method that will convert the riskIndex to proper color for you.

    E.g. Let say you create a utility class called DataRepresentationUtils which contains a method that calculates a proper color for given index:

    package web.utils;
    
    public class DataRepresentationUtils {
    
        private DataRepresentationUtils() { }
    
        public static String convertRiskIndexToRGBLiteral(int riskIndex) {
    
            // some logic here. Example of output: "#00ff00"
    
        }
    } 
    

    Then you can use that method inside your template in a following manner:

    <td th:text="${data.riskIndex}" th:styleappend="'background-color: ' + ${T(web.utils.DataRepresentationUtils).convertRiskIndexToRGBLiteral(data.riskIndex)} + ';'"></td>