简体   繁体   English

如何在Django模板中使用“不是不是”?

[英]How do I use 'is not None' in Django Templates?

I want to customize the greeting on my homepage so it's whether: 我要自定义主页上的问候语,因此它是:

When logged in and entered first name: 登录并输入名字时:

John! 约翰! Where do you want to go? 你想去哪里?

else: 其他:

Where do you want to go? 你想去哪里?

This is my template: 这是我的模板:

 {% if user.is_authenticated and not firstname_of_logged_user == None%}
 <h1 class="text-center" id="extraglow">{{firstname_of_logged_user}}! where do 
 you want to go?</h1></label>
{%else%}
<h1 class="text-center" id="extraglow">where do you want to go?</h1></label>
                                {%endif%}

However, it doesn't seem to pick up the "not None" part because if the user is logged in but didn't enter first name it shows like this: 但是,似乎没有选择“ not None”部分,因为如果用户登录但未输入名字,则显示如下:

! where do you want to go? 你想去哪里?

and if I say: 如果我说:

firstname_of_logged_user is not None

it says an error: 它说一个错误:

Unused 'is' at end of if expression. if表达式末尾未使用的'is'。

Seems like an easy thing but it's not working. 似乎很简单,但是却行不通。 What's wrong? 怎么了? Cheers! 干杯!

You can use the != operator instead of not . 您可以使用!=运算符,而不是not However, things can be simplified even further to: 但是,可以进一步简化以下内容:

{% if user.is_authenticated and firstname_of_logged_user %}

The above will check whether or not firstname_of_logged_user is truthy in your template. 上面的代码将检查firstname_of_logged_user在模板中是否为真。

The if template tag has supported the is operator since Django 1.10 ( release notes ). 自Django 1.10( 发行说明 )以来,if模板标记已支持is运算符。

You can now do {% if x is None %} and {% if x is not None %} . 现在,您可以执行{% if x is None %}{% if x is not None %}

The is operator is not supported. 不支持is运算符。 Just use {% if var != None %} . 只需使用{% if var != None %} This is not exactly the same but it will be sufficient for most cases. 这并不完全相同,但是对于大多数情况来说就足够了。

See supported operators here . 在此处查看支持的运算符

If you actually want to use the is operator, you would have to implement it as a custom template tag. 如果您实际上要使用is运算符,则必须将其实现为自定义模板标记。

For instance: 例如:

@register.filter
def is(lhs, rhs):
    return lhs is rhs

Thus you will be able to use it as: 因此,您可以将其用作:

{% if var1|is:var2 or not var3|is:var4 %}
    ...
{% else %}
    ...
{% endif %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM