275

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'
1
  • 5
    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.
    – mgilson
    Jan 8, 2013 at 12:30

2 Answers 2

544

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

{{ 'Update' if files else 'Continue' }}
6
  • 97
    A shorthand for {{ value if value else 'No value' }} would be {{ value or 'No value' }}
    – Don Grem
    Dec 30, 2014 at 11:39
  • 16
    @DorinGrecu My code is not full with {{ tobe or 'Not to be' }} thanks to you :)
    – dcohenb
    Mar 15, 2016 at 10:40
  • 22
    If you need to use a variable, you can use inside {% %} too. Like {% set your_var = 'Update' if files else 'Continue' %}
    – jhpg
    Jun 25, 2017 at 20:43
  • can it also contain markup like: {{ '<h4>Update</h4>' if files else '<h4>Continue</h4>' }}?
    – Macilias
    Feb 9, 2022 at 14:03
  • 1
    @Macilias depends on how autoescape is configured. If it's set to True, you may need to add the | safe filter.
    – bereal
    Feb 9, 2022 at 14:11
10

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

{{ files and 'Update' or 'Continue' }}
1
  • 3
    This construct is not really applicable in languages that interpret an empty string as falsy. True and '' or 'a' will evaluate to a, which is not what was intended. Jan 11, 2020 at 9:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.