Jinja2 shorthand conditional

Say I have this:

{% if files %}
    Update
{% else %}
    Continue
{% endif %}

In PHP, say, I can write a shorthand conditional, like:

<?php echo $foo ? 'yes' : 'no'; ?>

Is there then a way I can translate this to work in a jinja2 template:

'yes' if foo else 'no'

  • 4

    I don’t know if this helps, but the php expression looks a lot like what is called the “ternary operator” in C-like languages. The final line is called the “conditional expression” in python, although I’ve seen it called the ternary operator in python as well. Anyway, I mention it as it might help to know the names of those things in a google search.

    – 

Yes, it’s possible to use inline if-expressions:

{{ 'Update' if files else 'Continue' }}

Alternative way (but it’s not python style. It’s JS style)

{{ files and 'Update' or 'Continue' }}

Leave a Comment