G.Brown
G.Brown

Reputation: 213

How can you change the color of a jinja2 entry depending on some condition? (using flask)

I just worked through the flask tutorial, step by step creating a blog web application. The entries are rendered via a jinja template:

<ul class=entries>
    {% for entry in entries %}
        <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
    {% else %}
        <li><em>Unbelievable.  No entries here so far</em>
    {% endfor %}
  </ul>

The color is defined in a style.css:

a, h1, h2       { color: #377ba8; }

However, I really would like to be able, to switch the color of the entry depending on a condition. For example, if the entry.text is 'apples', it should be red, otherwise green.

Being a bloody noob to web development, I feel like something like this might be javascript, but I simply don't see how to accomplish this task and would appreciate your help.

Best,

gbrown

Upvotes: 3

Views: 11891

Answers (1)

poke
poke

Reputation: 388463

First of all, you should add a rule to your CSS so that you can change the color by applying a class to your element. Something like this:

.apples {
    color: red;
}

Then, you need to make your Jinja template apply a class attribute depending on the value of entry.text:

<ul class="entries">
    {% for entry in entries %}
        <li {% if entry.text == 'apples' %} class="apples" {% endif %}>
            <h2>{{ entry.title }}</h2>
            {{ entry.text|safe }}
        </li>
    {% else %}
        <li>
            <em>Unbelievable. No entries here so far.</em>
        </li>
    {% endfor %}
</ul>

This technique is described in the Jinja manual for example under the topic “Highlighting Active Menu Items”.

Upvotes: 7

Related Questions