Jinja2 条件简写

问题描述 投票:0回答:2

说我有这个:

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

在 PHP 中,比如说,我可以编写简写条件,例如:

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

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

'yes' if foo else 'no'
python jinja2 conditional-operator
2个回答
546
投票

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

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

10
投票

另一种方式(但不是Python风格,而是JS风格)

{{ files and 'Update' or 'Continue' }}
© www.soinside.com 2019 - 2024. All rights reserved.