Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional element classes with jinja, I want a div to get a class if a list item contains a certain item

I'm making a a little job board and I have little cards for each job. These cards are dynamically created from a list sent from my python script to the html using flask/jinja

jobs = [{'title':'fix car', 'description':'my car broke down', 'price':100}]

HTML example

{% for item in jobs %}

<p> {{ item['title'] }} {{ item['description'] }} {{ item['price'] }} </p>

{% endfor %}

Screenshot of job tasks

What I would like is to be able to make selected cards stand out, or featured. So in my Python script where the jobs come from I've added a binary option. 1 = featured, 0 = normal

So In my html it would look something like this:

{% for item in jobs %}

<p class='featured if item['featured']'> {{ item['title'] }} {{ item['description'] }} {{ item['price'] }}

{% endfor %}

so it would get a new CSS class if its featured key is set to 1.

CSS example

.featured {
    background-color: blue;
}
like image 846
Ari Avatar asked Apr 06 '19 03:04

Ari


Video Answer


1 Answers

You can use an inline conditional for a shorter result:

<p class='{{"featured" if item["featured"] else "normal"}}'> {{ item['title'] }} {{ item['description'] }} {{ item['price'] }}</p>

However, if you do not want to include a class for non-featured cards, a generic if-else statement can be used:

{%if item["featured"]%}
  <p class='featured'> {{ item['title'] }} {{ item['description'] }} {{ item['price'] }}</p>
{%else%}
  <p> {{ item['title'] }} {{ item['description'] }} {{ item['price'] }}</p>
{%endif%}
like image 57
Ajax1234 Avatar answered Oct 10 '22 18:10

Ajax1234