Python Jinja2 if 语句中的 vs 等于 dict

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

Jinja2 if statement in vs equals on dict

pythonif-statementjinja2

提问by TimothySwieter

I'm new to Jinja2 and using it as part of Flask. I've got two statements below. The one with "in" works. The one with "equals" isn't. The equals version is getting a syntax error shown below. I'm curious as to why, as the way the equals version is written, to me at least, is easier to read.

我是 Jinja2 的新手,并将其用作 Flask 的一部分。我在下面有两个声明。带有“in”的那个作品。带有“等于”的那个不是。equals 版本出现如下所示的语法错误。我很好奇,为什么编写 equals 版本的方式,至少对我来说,更容易阅读。

{% if "SN" in P01["type"] %}
  {% include 'sn.html' %}
{% endif %}

{% if P01["type"] equals "SN" %}
  {% include 'sn.html' %}
{% endif %}

The errors message from jinja2.exceptions.TemplateSyntaxError

来自 jinja2.exceptions.TemplateSyntaxError 的错误消息

TemplateSyntaxError: expected token 'end of statement block', got 'equals'

TemplateSyntaxError:预期标记“语句块结束”,得到“等于”

Thank you.

谢谢你。

采纳答案by Andrew Clark

In Jinja2 you would use ==instead of equals, for example:

在 Jinja2 中,您将使用==代替equals,例如:

{% if P01["type"] == "SN" %}
  {% include 'sn.html' %}
{% endif %}

http://jinja.pocoo.org/docs/switching/#conditions

http://jinja.pocoo.org/docs/switching/#conditions

I'm pretty sure this is what you are looking for, but you should note that this has a different meaning than "SN" in P01["type"], using inis a substring test, so for example "foo" in "foobar"would be True.

我很确定这就是您要查找的内容,但是您应该注意,这与 具有不同的含义"SN" in P01["type"], usingin是子字符串测试,因此例如"foo" in "foobar"为 True。