什么是“无"?在Django模板中? [英] What is the equivalent of "none" in django templates?
问题描述
我想看看Django模板中是否没有字段/变量.正确的语法是什么?
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%}
在上面的示例中,我将用什么来替换空"?
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模板中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!