Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'if' statement in jinja2 template

I'm trying to write an if statement in jinja template:

{% for key in data %}     {% if key is 'priority' %}         <p>('Priority: ' + str(data[key])</p>     {% endif %} {% endfor %} 

the statement I'm trying to translate in Python is:

if key == priority:     print(print('Priority: ' + str(data[key])) 

This is the error i'm getting:

TemplateSyntaxError: expected token 'name', got 'string'

like image 284
Luisito Avatar asked Nov 15 '16 22:11

Luisito


People also ask

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.

How are variables in Jinja2 templates specified?

A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine. A template contains variables and/or expressions, which get replaced with values when a template is rendered; and tags, which control the logic of the template.


2 Answers

Why the loop?

You could simply do this:

{% if 'priority' in data %}     <p>Priority: {{ data['priority'] }}</p> {% endif %} 

When you were originally doing your string comparison, you should have used == instead.

like image 168
Nick Avatar answered Sep 30 '22 01:09

Nick


We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}      <p> Something is True </p> {% else %}      <p> Something is False </p> {% endif %} 
like image 20
Michel Fernandes Avatar answered Sep 30 '22 00:09

Michel Fernandes