有条件的Jinja2速记


190

说我有这个:

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

比方说,在PHP中,我可以写一个简写的条件语句,例如:

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

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

'yes' if foo else 'no'

我不知道这是否有帮助,但是php表达式看起来很像用C语言编写的“三元运算符”。最后一行在python中称为“条件表达式”,尽管我也看到它在python中也称为三元运算符。无论如何,我提到它是因为它可能有助于在Google搜索中了解这些名称。
— mgilson

Answers:


369

是的,可以使用内联if-expressions:

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

77
简写为{{ value if value else 'No value' }}是{{ value or 'No value' }}
— 唐GREM

12
@DorinGrecu{{ tobe or 'Not to be' }}感谢您,我的代码不完整:)
— dcohenb

15
如果需要使用变量,也可以使用inside {% %}。喜欢{% set your_var = 'Update' if files else 'Continue' %}
— jhpg

2
@dcohenb,请单独提出一个问题。;)
— deed02392

4

另一种方法(但这不是python样式。它是JS样式)

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

1
此构造实际上不适用于将空字符串解释为虚假的语言。True and '' or 'a'将计算为a,这不是预期的。
— 加布里埃尔·雅布隆斯基

但是python3将空字符串解释为False。因此,如果您编写'' or 'a'python将回答'a'。因此,您的评论可以与Ruby相关,例如
— user3713526
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.