【问题标题】:How to color html table in django based on condition如何根据条件在 django 中为 html 表着色
【发布时间】:2022-01-03 05:52:00
【问题描述】:

如何根据这些条件为Class 11 着色:

  • 如果值 > 20 则着色为红色
  • 如果值 > 40 则为橙色
  • 如果值 > 50 则为绿色

我在网上搜索并发现只有 JS 的方式来做这件事,但我对 JavaScript 还是很陌生。我想知道是否有办法用 CSS 做到这一点?

【问题讨论】:

标签: html css django


【解决方案1】:

你可以在 html 中做一堆 if/then/else。

这是您的 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>

这是我为上下文创建的视图:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-03
    • 2019-11-12
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 2023-04-07
    • 2012-02-03
    相关资源
    最近更新 更多