[Fixed]-Create template tags from the current function

1👍

Now we’ve seen the total nonsense answer, here’s the no-nonsense one:

In your yourapp/templatetags/yourapptags.py module:

from django import template
register = template.Library()

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

DEFAULT_LANG = 'fr'

@register.simple_tag
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)

Then in your template:

{% load "yourapptags" %}

<p>EN : {% localdate 'en' %}</p>
<p>FR : {% localdate 'fr' %}</p>

Note that this is for forcing date formatting / localisation in a given locale whatever the current locale is which in this case seems quite weird to me.

If what you really want is just to display the current date formatted according to the current visitor’s locale (cf https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#how-django-discovers-language-preference), you can just get rid of the lang argument and use translation.get_language() instead:

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

Also note that l10n formats files provided by Django already have some date formats defined and that you can override them.

Leave a comment