Skip to content Skip to sidebar Skip to footer

Create Template Tags From The Current Function

I have formally constructed the function in my models.py file : from datetime import datetime from django.template.defaultfilters import date as datefilter from django.utils impor

Solution 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_tagdeflocaldate(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()
    returndatefilter(now, fmt)

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

Post a Comment for "Create Template Tags From The Current Function"