Search code examples
djangojinja2django-i18n

Django+Jinja2+i18n: jinja2.exceptions.UndefinedError: 'gettext' is undefined


I'm trying since many hours to get things work, but still without success. I use Jinja2 with Django (https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.jinja2.Jinja2) and now I try to enable translations. Jinja2 docs suggest (http://jinja.pocoo.org/docs/2.9/extensions/#i18n-extension) existing extension (jinja2.ext.i18n). So my configuration looks like this:

settings.py

TEMPLATES = [
{
    "BACKEND": "django.template.backends.jinja2.Jinja2",
    "DIRS": [os.path.join(BASE_DIR, 'templates')],
    "APP_DIRS": False,
    'OPTIONS' : {
        'environment': 'config.jinja2.environment'
    }
}]

jinja2.py:

def environment(**options):
    env = Environment(**options, extensions=['jinja2.ext.i18n'])
    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
        'dj': defaultfilters
    })
    return env

within template:

{{ gettext('...') }}

result:

jinja2.exceptions.UndefinedError: 'gettext' is undefined

Does anyone know what the problem is and what I miss? thanks for help in advance!


Solution

  • Here is my solution after many tries. The 'jinja2.ext.i18n' doesn't install gettext automatically, so you need to add it first to the Environment via install_gettext_callables:

    from django.utils.translation import gettext, ngettext
    
    def environment(**options):
        env = Environment(**options, extensions=['jinja2.ext.i18n'])
    
        env.install_gettext_callables(gettext=gettext, ngettext=ngettext, newstyle=True)
    
        env.globals.update({
            'static': staticfiles_storage.url,
            'url': reverse,
            'dj': defaultfilters
        })
        return env