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

The data of my html table is from this list:

[{'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">

{% for element in mylist %}

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

      {% endfor %}      

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:

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

Leave a Reply