Issue
For the first line below, the jinja2 template renders whether x
exists or not. However, in the second line, the template only renders if x
is an existing list. If it isn't I get an error (assume if x
exists it is always a list with at least one item):
<p>x: {{ x }}</p>
<p>x[0]: {{ x[0] }}</p>
UndefinedError: 'x' is undefined
Is there a better way to check if a variable exists and get its first item than what I have here (I have tons of instances of x
which have much longer names in my template and I'd rather not wrap it with the if clause every time):
{% if x %}
<p>x[0]: {{ x[0] }}</p>
{% endif %
Solution
Jinja supports inline if else
statements, and unlike Python also allows omitting the else
.
{{ x[0] if x }}
Answered By - davidism
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.