Python jinja2速记有条件

Ahm*_*man 153 python jinja2

说我有这个:

{% if files %}
    Update
{% else %}
    Continue
{% endif %}
Run Code Online (Sandbox Code Playgroud)

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

<?php echo $foo ? 'yes' : 'no'; ?>
Run Code Online (Sandbox Code Playgroud)

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

'yes' if foo else 'no'
Run Code Online (Sandbox Code Playgroud)

ber*_*eal 305

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

{{ 'Update' if files else 'Continue' }}
Run Code Online (Sandbox Code Playgroud)

  • `{{value if value else'No value'}}`的简写将是`{{value或'No value'}}` (64认同)
  • 如果你需要使用变量,你也可以在`{%%}`里面使用.比如`{%set your_var ='Update',如果文件别'继续'%}` (9认同)
  • @DorinGrecu我的代码不满``{{tobe或'不是'}}`谢谢你:) (8认同)

use*_*526 6

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

{{ files and 'Update' or 'Continue' }}
Run Code Online (Sandbox Code Playgroud)

  • 这种构造实际上并不适用于将空字符串解释为假的语言。`True and '' or 'a'` 将计算为 `a`,这不是预期的结果。 (3认同)