why is flask jinja giving me error when I use this {{bg_color}} as a background Color

81 Views Asked by At

this is my code i want to give different colors to comments like grey(#eee) to odd and blue (#e6f9ff) to even

here this line is giving me error

background-color: {{ bg_color }}

{% extends 'base.html' %}

{% block content %}
    <h1>{% block title %} Comments {% endblock %}</h1>
    <div style="width: 50%; margin: auto">
        {% for comment in comments %}
            {% if loop.index % 2 == 0 %}
                {% set bg_color = '#e6f9ff' %}
            {% else %}
                {% set bg_color = '#eee' %}
            {% endif %}

            <div style="padding: 10px; background-color: {{ bg_color }}; margin: 20px">
                <p>#{{ loop.index }}</p>
                <p style="font-size: 24px">{{ comment }}</p>
            </div>
        {% endfor %}
    </div>
{% endblock %}

I think jinja version is updated and my course which Im following is old so anyone who knows to answer me

1

There are 1 best solutions below

0
On

You should note the scope for the variables. If you define a variable within an if-else block, it is only valid there.

<div style="width: 50%; margin: auto">
    {% for comment in comments -%}
    {% set bg_color = '#e6f9ff' if loop.index % 2 == 0 else '#eee' %}
    <div style="padding: 10px; background-color: {{ bg_color }}; margin: 20px">
        <p>#{{ loop.index }}</p>
        <p style="font-size: 24px">{{ comment }}</p>
    </div>
    {% endfor -%}
</div>

Instead of using jinja you can also use css to assign a different background color to every other line.

<div class="comments">
    {% for comment in comments -%}
    <div>
        <p>#{{ loop.index }}</p>
        <p class="text">{{ comment }}</p>
    </div>
    {% endfor -%}
</div>

<style type="text/css">
    .comments {
        width: 50%; 
        margin: auto;
    }

    .comments div {
        padding: 10px; 
        background-color: #e6f9ff;
        margin: 20px
    }

    .comments div:nth-child(odd) {
        background-color: #eee;
    }

    .comments .text {
        font-size: 24px
    }
</style>