本文介绍了“无"的等价物是什么?在 Django 模板中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查看 Django 模板中的字段/变量是否为 none.什么是正确的语法?

I want to see if a field/variable is none within a Django template. What is the correct syntax for that?

这是我目前拥有的:

{% if profile.user.first_name is null %}
  <p> -- </p>
{% elif %}
  {{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif%}

在上面的例子中,我会用什么来替换null"?

In the example above, what would I use to replace "null"?

推荐答案

None、False 和 True 在模板标签和过滤器中都可用.None, False、空字符串 ('', "", """""") 和空列表/元组都评估为 False 当被 if 评估时,你可以很容易地做到

None, False and True all are available within template tags and filters. None, False, the empty string ('', "", """""") and empty lists/tuples all evaluate to False when evaluated by if, so you can easily do

{% if profile.user.first_name == None %}
{% if not profile.user.first_name %}

提示:@fabiocerqueira 是对的,将逻辑留给模型,将模板限制为唯一的表示层,并在您的模型中计算类似的东西.一个例子:

A hint: @fabiocerqueira is right, leave logic to models, limit templates to be the only presentation layer and calculate stuff like that in you model. An example:

# someapp/models.py
class UserProfile(models.Model):
    user = models.OneToOneField('auth.User')
    # other fields

    def get_full_name(self):
        if not self.user.first_name:
            return
        return ' '.join([self.user.first_name, self.user.last_name])

# template
{{ user.get_profile.get_full_name }}

希望这有帮助:)

这篇关于“无"的等价物是什么?在 Django 模板中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:50
查看更多