Ruth Young
Ruth Young

Reputation: 888

Is it better to use Django template tags or pass variables from python

I'm displaying a date on a Django template, and I have a python function that formats the date today for me and passes it to my template.

# function [format example: Wednesday 01 February 10:00:00]
def today():
    date_now = datetime.now()
    day_number = date_now.strftime("%d")
    month_name = date_now.strftime("%B")
    day_name = date_now.strftime("%A")
    time = date_now.strftime("%X")
    date = "{} {} {} {}".format(day_name, day_number, month_name, time)
    return date

# view
def myview(request):
    the_date_today = today()
    context = {
        "the_date_today": the_date_today,
    }
    return render(request, "template.html", context)

# template
<h1>{{ the_date_today }}</h1>

I've just found a way of doing this just with Django template tags.

# view
def myview(request):
    the_date_today = datetime.now()
    context = {
        "the_date_today": the_date_today,
    }
    return render(request, "template.html", context)

# template
<h1>{{ the_date_today|date:"l m F H:i" }}</h1>

What's the better approach for this? It's a lot less code to just use template filters, but does this make anything slower?

Upvotes: 1

Views: 573

Answers (1)

mhawke
mhawke

Reputation: 87064

The template method is better. It's not going to be slower.

If later on you need to modify the display format you can do so by simply modifying the template, not the code.

What's more, you don't even need to pass the value for the_date_today to the template because you can call now in the template:

<h1>{% now "l d F H:i" %}</h1>

Upvotes: 4

Related Questions