Conditionally highlight cells in a html table based on the cells' value

The data of my html table is from this list:

mylist=
[{'StartDate': '2021-10-02', 'ID': 11773, 'Name': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Name': Jane, 'Days':65}, 
{'StartDate': '2021-10-03', 'ID': 95453, 'Name': Jane, 'Days':65}, 
{'StartDate': '2021-10-03', 'ID': 15673, 'Name': Mike, 'Days':65}, 
... 
{'StartDate': '2021-10-5', 'ID': 34653, 'Name': Jack, 'Days':63}]

My HTML table in my HTML file is:

<table class="table table-striped" id="dataTable" width="100%" cellspacing="0">
                                    
     <thead>
        <tr>
            <th>StartDate</th>
            <th>ID</th>
            <th>Name</th>
            <th>Days</th>
        
     </thead>
     <body>

{% for element in mylist %}

      <tr>
        <td>{{ element.StartDate}}</td>
        <td>{{ element.ID }}</td>
        <td>{{ element.Receiver }}</td>
        <td>{{ element.Days }}</td>

       </tr>
      {% endfor %}      
       </tbody>
                         
      </table>

I want to set the color of days that are larger than 14 into Red color. And I want to set the cells that contain "Mike" in Red and "Jane" in Blue.

Please advise what I should do

>Solution :

Django has if statement template tags that can be used for this.

For example, for your days section you could write your <td> element like this in your template:

<td {% if element.Days > 14 %} class="red_class"{% endif %}>{{ element.Days }}</td>

You would then define a css class named red_class and set the background color attribute of that element to red.

The name part would be similar:

<td 
   {% if element.Receiver == "Mike" %} 
      class="red_class"
   {% elif element.Receiver == 'Jane' %}
      class="blue_class"
   {% endif %} > {{ element.Receiver }}</td>

Leave a Reply