相当于“无”在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%}
在上面的例子中,我将用什么来替换null?
In the example above, what would I use to replace "null"?
推荐答案
无,False和True
都可以在模板标签和过滤器中使用。 None,False
,空字符串('',,
)和空列表/ code> f $ 如果
如果
,则可以轻松地执行 c $ c> $ t
$ b
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屋!