user13286706
user13286706

Reputation:

How to color html table in django based on condition

How can I color Class 11 based on those conditions:

I searched web and foun only JS ways doing it but I am quite new with JavaScript. I was wondering if there is a way to do it with CSS?

Upvotes: 0

Views: 853

Answers (1)

onosendi
onosendi

Reputation: 2277

You could do a bunch of if/then/else in the html.

Here's your HTML:

<html>
<head>
  <style>
    .red {
      color: red;
    }

    .orange {
      color: orange !important;
    }

    .green {
      color: green;
    }
  </style>
</head>

<body>
<table>
  <tr>
    <th>A</th>
    {% for item in a %}
      {% if item > 50 %}
      <td class="green">{{ item }}</td>
      {% elif item > 40 %}
      <td class="orange">{{ item }}</td>
      {% elif item > 20 %}
      <td class="red">{{ item }}</td>
      {% else %}
      <td>{{ item }}</td>
      {% endif %}
    {% endfor %}
  </tr>
  <tr>
    <th>B</th>
    {% for item in b %}
      {% if item > 50 %}
      <td class="green">{{ item }}</td>
      {% elif item > 40 %}
      <td class="orange">{{ item }}</td>
      {% elif item > 20 %}
      <td class="red">{{ item }}</td>
      {% else %}
      <td>{{ item }}</td>
      {% endif %}
    {% endfor %}
  </tr>
</table>
</body>
</html>

And here's the view I created for context:

from django.views.generic import TemplateView


class View(TemplateView):
    template_name = 'view.html'

    def get_context_data(self, **kwargs):
        kwargs.update({
            'a': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
            'b': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
        })
        return super().get_context_data(**kwargs)

Upvotes: 1

Related Questions