Search code examples
pythonhtmlcssflaskjinja2

How to make dynamic css colours in flask


In my app.py, I have a list of distionaries like: list=[{'grade':0,'colour':(0,0,0)},{'grade':10', colour':(0,0,0)},{'grade':5',colour':(0,0,0)}, where grade can be anywhere between 0 and 10. (Some keys are removed to provide simplicity). I then assign each item a colour based on their grade like this: (using rgb(red,green,blue) format)

for i in list:
    green = i['grade'] * 25.5
    red = 255 - green 
    i['colour'] = (red,green,0)

and my flask route:

@app.route('/dashboard')
def dashboard():
    return render_template('dashboard.html', list=list)

My dashboard.html file contains

{% block content %}
  {% for i in list %}
    <h3 style="color:rgb({{i['color']}});text-align:center;">{{i['grade']}} </h3>
  {% endfor %}
{% endblock %} 

However, this does not work the same way as <h3 style="color:rgb(255,0,0)>, and it throws errors stating ) expected, at-rule or selector expected, { expected, at-rule or selector expected I am looking for any way or workaround around this problem.


Solution

  • The color values you generate are part of a tuple. To use this in the CSS statement, you should concatenate the sequence into a string using a delimiter. The jinja filter join is suitable for this.

    When choosing your variable names, keep in mind that you could cover up existing keywords.

    @app.route('/dashboard')
    def dashboard():
    
        items=[
            {'grade':0,'colour':(0,0,0)},
            {'grade':10, 'colour':(0,0,0)},
            {'grade':5, 'colour':(0,0,0)}
        ]
        
        for item in items:
            green = item['grade'] * 25.5
            red = 255 - green 
            item['colour'] = (red,green,0)
        
        return render_template('dashboard.html', **locals())
    
    {% for item in items %}
    <h3 style="color: rgb({{ item.colour | join(',') }});">{{ item.grade }}</h3>
    {% endfor %}