Jinja2 shorthand conditional

PythonJinja2Conditional Operator

Python Problem Overview


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'

Python Solutions


Solution 1 - Python

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

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

Solution 2 - Python

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAhmed NuamanView Question on Stackoverflow
Solution 1 - PythonberealView Answer on Stackoverflow
Solution 2 - Pythonuser3713526View Answer on Stackoverflow