271

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'
dreftymac
  • 31,404
  • 26
  • 119
  • 182
Ahmed Nuaman
  • 12,662
  • 15
  • 55
  • 87
  • 3
    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 08 '13 at 12:30

2 Answers2

531

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

{{ 'Update' if files else 'Continue' }}
bereal
  • 32,519
  • 6
  • 58
  • 104
  • 96
    A shorthand for `{{ value if value else 'No value' }}` would be `{{ value or 'No value' }}` – Don Grem Dec 30 '14 at 11:39
  • 16
    @DorinGrecu My code is not full with `{{ tobe or 'Not to be' }}` thanks to you :) – dcohenb Mar 15 '16 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 '17 at 20:43
  • can it also contain markup like: {{ '

    Update

    ' if files else '

    Continue

    ' }}?
    – Macilias Feb 09 '22 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 09 '22 at 14:11
  • What to do in following condition `{{ "Whoops" if message.tags == 'danger' else message.tags }}` – TarangP Apr 26 '22 at 12:58
11

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

{{ files and 'Update' or 'Continue' }}
user3713526
  • 435
  • 7
  • 16
  • 2
    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. – Gabriel Jablonski Jan 11 '20 at 09:12