Search code examples
djangotemplatetag

Adapt a template tags method


I am trying to use a template tags in a template.

from django import template
from datetime import datetime
from django.template.defaultfilters import date as datefilter
from django.utils import translation

register = template.Library()

DATE_FORMATS = {
    "en":  "l, F j, Y",
    "fr": "l, j F Y"
}

DEFAULT_LANG = 'fr'

@register.simple_tag(name="localdate")
def localdate(lang=DEFAULT_LANG):
    fmt = DATE_FORMATS.get(lang, DATE_FORMATS[DEFAULT_LANG])
    now = datetime.now()
    with translation.override(lang):
        return datefilter(now, fmt)

I tried to use {{ localdate : 'en'}}, but everything went wrong. Is there an easy way to adapt tags so that it works? In fact, the file is called date_tags.py. So in the template I load the file with {%load date_tags %}.

Thanks in advance!


Solution

  • It looks like you're incorrectly using the template tag.

    Try using this:

    {% localdate "en" %}
    

    For more information, check out the docs here: Django Simple Tag