2015-01-26 91 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 %}