Django:在模板中过滤日期字段
Django : filter Datefield in template
我正在使用 Django 1.5.8
我想过滤 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) %}
吗?
或者我必须制作新的自定义过滤器吗?
虽然我确信可以使用自定义模板标记来执行此操作,但我认为您会发现在模型代码中实现此测试要容易得多。例如:
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 %}
我正在使用 Django 1.5.8
我想过滤 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) %}
吗?
或者我必须制作新的自定义过滤器吗?
虽然我确信可以使用自定义模板标记来执行此操作,但我认为您会发现在模型代码中实现此测试要容易得多。例如:
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 %}