如何处理模板中复杂的分支?

时间:2014-10-19 08:04:10

标签: django model-view-controller django-templates

我有一张这样的表:

class Book(models.Model):
    title=models.Charfield(blank=True, ...)
    date=models.Charfield(blank=True, ...)
    author=models.Charfield(blank=True, ...)
    ...

我需要像这样显示以下信息:<p>Title (date), author</p> 但问题是所有这些字段都是可选的,这使我在模板中创建了这个怪异的构造:

{% if book.title or book.date or book.author %}
    <p>
    {% if book.title %}
        {{ book.title }}
    {% endif %}
    {% if book.date %}
        ({{ book.date }})
    {% endif %}
    {% if book.title or book.date and book.author %}
        ,
    {% endif %}
    {% if book.author %}
        {{ book.author }}
    {% endif %}
    </p>
{% endif %}

应该是这样还是我做错了什么? 我应该将这个逻辑移到模型中,在那里我可以用python等更清洁的方式来做它吗?

1 个答案:

答案 0 :(得分:0)

在模型中:

def __unicode__(self):
    p = []
    if self.title:
        p.append(self.title)
    if self.date:
        p.append(u'(%s)' % self.data)
        p = [u' '.join(p)]
    if book.author:
        p.append(book.author)  # p.append(unicode(book.author))
    return u', '.join(p)            

def as_p(self):
    p = unicode(self)
    return u'<p>%s</p>' % p if p else u''

在模板中:

{{ book.as_p }}