Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

python - Color coding cells in a table based on the cell value using Jinja templates

I have a simple flask app and need to display a table of values, with the cell backgrounds colour coded based on the cell value according to thresholds. I'm generating the table content as follows:

  {% block dashboard_table2 %}
      <table>
      {% for row in data %}
          {% for item in row %}
              <td>{{ item }}</td>
          {% endfor %}
      </tr>
      {% endfor %}
      </table>
  {% endblock %}

I tried wrapping the values in style tags like this in Python but it didn't work:

  if int(value) <= 10:
      value = '<p style="background-color:Red">' + value + '</p>'

I'm guessing the CSS for the page is overriding the style attribute. I also tried just setting the text color attribute instead of background-color but no dice. Any suggestions on a good way to do this? I'd like to have a concise way to specify threshold values that aren't hard-coded in the templates.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The easiest way would be to put this display logic in your template:

<table>
    {% for row in data %}
    <tr>
        {% for item in row %}
            {% if item <= 10 %}
                <td class="under-limit">{{ item }}</td>
            {% else %}
                <td>{{ item }}</td>
            {% endif %}
        {% endfor %}
    </tr>
    {% endfor %}
</table>

Then, in your CSS you can use:

.under-limit { background-color: red; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...