238

说我有这个:

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

比如说,在 PHP 中,我可以编写一个速记条件,例如:

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

那么有没有一种方法可以将其翻译为在 jinja2 模板中工作:

'yes' if foo else 'no'
4

2 回答 2

459

是的,可以使用内联 if 表达式

{{ 'Update' if files else 'Continue' }}
于 2013-01-08T12:32:08.050 回答
8

另一种方式(但它不是python风格。它是JS风格)

{{ files and 'Update' or 'Continue' }}
于 2019-11-20T12:13:07.587 回答