Python jinja2 简写条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14214942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:46:28 来源:igfitidea点击:
Python jinja2 shorthand conditional
提问by Ahmed Nuaman
Say I have this:
说我有这个:
{% if files %}
Update
{% else %}
Continue
{% endif %}
In PHP, say, I can write a shorthand conditional, like:
例如,在 PHP 中,我可以编写一个速记条件,例如:
<?php echo $foo ? 'yes' : 'no'; ?>
Is there then a way I can translate this to work in a jinja2 template:
那么有没有一种方法可以将其转换为在 jinja2 模板中工作:
'yes' if foo else 'no'
采纳答案by bereal
Yes, it's possible to use inline if-expressions:
是的,可以使用内联 if 表达式:
{{ 'Update' if files else 'Continue' }}
回答by user3713526
Alternative way (but it's not python style. It's JS style)
另一种方式(但它不是python风格。它是JS风格)
{{ files and 'Update' or 'Continue' }}

