Изменение цвета ячеек Условное форматирование Django HTML

В моем HTML представлении есть таблица, в которой я хочу, чтобы фон ячеек менялся, когда в ячейке находится определенное значение. Вот скриншот моей таблицы в HTML. Значения заполняются с помощью простого цикла for в моих представлениях Django. В приложении вы увидите css и HTML. В верхней части таблицы вы увидите легенду. Например, если значение в любом теге td == 6, сделайте фон ячейки rgb(1, 109, 167). Это то, чего я пытаюсь достичь. Спасибо

  <div class="table-responsive">
                        <table class="table" id="scores">
                      <thead>
                   
                        <tr>
                          <td rowspan="3"></td>
                          <th colspan="3" scope="colgroup">Reasoning</th>
                          <th colspan="3" scope="colgroup">Executive Functions</th>
                          <th colspan="2" scope="colgroup">Speed</th>
                          <th colspan="2" scope="colgroup">Memory</th>
                        </tr>
                        <tr>
                          <th scope="col">Verbal</th>
                          <th scope="col">Spatial</th>
                          <th scope="col">Abstract</th>
                          <th scope="col">Flexible</th>
                          <th scope="col">Working Memory</th>
                          <th scope="col">Attention</th>
                          <th scope="col">Processing</th>
                          <th scope="col">Visual Motor</th>
                          <th scope="col">Verbal</th>
                          <th scope="col">Visual </th>
                          </tr>
                      </thead>
                      {% for i in scores %}
                      <tbody>
                      <tr>
                      <td>{{i.test_date}}</td>
                      <td>{{i.reasoning_verbal }}</td>
                      <td>{{i.reasoning_spatial}}</td>
                      <td>{{i.reasoning_abstract}}</td>
                      <td>{{i.executive_flexibility}}</td>
                      <td>{{i.executive_working_memory}}</td>
                      <td>{{i.executive_attention}}</td>
                      <td>{{i.speed_processing}}</td>
                      <td>{{i.speed_visual_motor}}</td>
                      <td>{{i.memory_verbal}}</td>
                      <td>{{i.memory_visual}}</td>
                      </tr>
                      </tbody>
                      {% endfor %}
                      </table>

#d6
{
    background-color: rgb(1, 109, 167);
    color: black;
}
#d5
{
    background-color: rgb(1, 167, 164);
    color: black;
}
#d4
{
    background-color: rgb(154, 191, 80);
    color: black;
}
#d3
{
    background-color: rgb(228, 190, 36);
    color: black;
}
#d2
{
    background-color: rgb(214, 142, 33);
    color: black;
}
#d1
{
    background-color: rgb(187, 185, 182);
    color: black;
}

Table

Похоже, вы используете bootstrap, поэтому вот пример с классом bootstrap. Однако вы можете с таким же успехом написать свой собственный класс.

Язык шаблонов Django может работать внутри ваших html-тегов, как например:

<td class="{% if i.your_var == 6 %}table-warning{% endif %}">{{i.your_var}}</td>

Если переменная равна 6, ячейка будет красной. Если у вас много различных сценариев или типов переменных и диапазонов, которые необходимо обработать, подумайте о написании пользовательского тега фильтра:

{% load my_color_filter %}

<td class="{{i.my_var|my_color_filter}}">{{i.your_var}}</td>

my_color_filter.py

from django import template
register = template.Library()

@register.filter()
def my_color_filter(my_var):
    if my_var == 6:
        td_class = 'someClass'
    elif my_var > 6:
        td_class = 'someOtherClass'
    # and so on...

    return td_class

Вы можете узнать больше о пользовательских тегах фильтров здесь в Django Docs.

Вернуться на верх