Home > Blockchain >  How to colorize list rendered to html via flask render_template
How to colorize list rendered to html via flask render_template

Time:10-27

I'm passing a list having values -

{"StudentName":"Name1", "Status":"Present"},
{"StudentName":"Name2", "Status":"Absent"}

to a html page via flask render_template()

I'm able to print the list in html page.

How to extract individual element from list and colorize them based on status. Eg.

Status: Present -- should be in GREEN color

Status : Absent -- should be in RED Color

CodePudding user response:

I would assume there is <li> in your code. I don't know the name of the dict you pass in your template so i would call it data.

You can try something like that each time you make a list item:

<ul>
{% for item in data %}
{% if item["Status"]=="Present" %}
    <li style="color:green;"> {{ item["StudentName"] }} </li>
{% else %}
    <li style="color:red;"> {{ item["StudentName"] }} </li>
{% endif %}
{% endfor %}
<ul>

You can also give a class to your list item <li > or <li > then add some CSS between <style> and </style> or in external css file.

.student-present{
    color:green;
}
.student-absent{
    color:red;
}

The second solution is better if you have a lot of formatting to do, or you will have a big and unreadable style attribute in all your items. Use an external css file if you have a lot of modification in different HTML element, or your style will be too big and make your template unreadable.

Using an external CSS file is the best solution, but style attribute can save time for small project with few modification.

Check out the flask template doc : https://flask.palletsprojects.com/en/0.12.x/tutorial/templates/

And basic CSS stuff : https://www.w3schools.com/css/

On the other hand, you could use JS to check for your list value and add style to it, but it would require waiting for the JS to be done before the color appears, and make it more complex, and I don't think it's the solution you need right now.

  • Related