Python jinja2 模板中的“if”语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40620823/
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-19 23:44:54  来源:igfitidea点击:

'if' statement in jinja2 template

pythontemplatesjinja2

提问by Luisito

I'm trying to write an if statement in jinja template

我正在尝试在 jinja 模板中编写 if 语句

{% for key in data %}
    {% if key is 'priority' %}
        <p>('Priority: ' + str(data[key])</p>
    {% endif %}
{% endfor %}

the statement I'm trying to translate in python is

我试图在 python 中翻译的语句是

if key == priority:
    print(print('Priority: ' + str(data[key]))

This is the error i'm getting:

这是我得到的错误:

TemplateSyntaxError: expected token 'name', got 'string'

TemplateSyntaxError:预期标记“名称”,得到“字符串”

回答by Nick

Why the loop?

为什么是循环?

You could simply do this:

你可以简单地这样做:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used ==instead.

当您最初进行字符串比较时,您应该使用它==

回答by Michel Fernandes

We need to remember that the {% endif %}comes after the {% else %}.

我们需要记住的是,{% endif %}来到后{% else %}

So this is an example:

所以这是一个例子:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}