2015-01-26 92 views
0

过滤的DateField我使用Django的1.5.8Django的:在模板

我想在模板过滤Datefield类型的数据,如下面的代码。

  • 表达对timesince格式近期的文章
  • 表达对date格式旧文章

some_template.html

{% for article in articles %} 

    {# recent articles #} 
    {% if article.created >= (now - 7 days) %} 
     {{ article.created|timesince }} 

    {# old articles more than one week past #} 
    {% else %} 
     {{ article.created|date:"m d" }} 
    {% endif %} 

{% endfor %} 

是否有处理由Django的{% if article.created >= (now - 7 days) %}的解决方案自己的模板标签?

或者我是否必须制作新的自定义过滤器?

回答

2

尽管我确定可以使用自定义模板标签来完成此操作,但我认为您会发现在模型代码中实现此测试要容易得多。例如:

from datetime import date, timedelta 
class Article(models.Model): 
    [...] 
    def is_recent(self): 
     return self.created >= date.today() - timedelta(days=7) 

那么你的模板可以是:

{% for article in articles %} 
    {% if article.is_recent %} 
    {{ article.created|timesince }} 
    {% else %} 
    {{ article.created|date:"m d" }} 
    {% endif %} 
{% endfor %}