Krystian Cybulski
Krystian Cybulski

Reputation: 11108

How to conditionally output a year when showing date in a Django template

I have an app which shows dates. I would like to print a date in the F j format if the year of the date is the same as the current year, and in F j, Y format if it is different. I would consider this to be presentation logic and would like to encapsulate this in template code, without modifying my views.

Ideally, I would like something like:

{{ the_date|date:'F j' }}{% if the_date.year == now.year %}{{ the_date|date:', Y' }}{% endif %}

The issue is that I cannot find a way of getting the current year in a way that can be used within an if tag. I know I could just include a today_dt in my template and compare against that. However, I am wondering if there is a way of not having to modify my views.

Upvotes: 0

Views: 870

Answers (1)

Stuart Leigh
Stuart Leigh

Reputation: 856

You should probably use a custom template tag filte (https://docs.djangoproject.com/en/dev/howto/custom-template-tags/) Would look something like

import datetime

from django import template
from django.utils.dateformat import format

register = template.Library()

@register.filter
def custom_date(date):
    now = datetime.datetime.now()
    if date.year == now.year:
        return format(date, 'F j')
    return format('F j, Y')

then in your template

{% load custom_tags %}

{{ the_date|custom_date }}

Upvotes: 3

Related Questions