Opened 5 years ago

Closed 5 years ago

Last modified 5 years ago

#16690 closed New feature (worksforme)

Add translation.activate decorator/context manager

Reported by: Ralph Broenink Owned by: nobody
Component: Internationalization Version: 1.3
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Currently, internationalization outside of templates and views requires several lines of code, identically each time:

from django.utils import translation
def welcome_translated(language):
    cur_language = translation.get_language()
    try:
        translation.activate(language)
        text = translation.ugettext('welcome')
    finally:
        translation.activate(cur_language)
    return text

(source: https://docs.djangoproject.com/en/dev/howto/i18n/)

However, this could easily be fitted within both decorators and context managers, allowing the following syntax:

@translation.activate(language)
def welcome_translated(language):
    return translation.ugettext('welcome')

or

def welcome_translated(language):
    with translation.activate(language):
        return translation.ugettext('welcome')

This would decrease the lines of code and the developer would not have to care for the case when the execution somehow fails and forgets to add the try/finally clause.

Change History (3)

comment:1 Changed 5 years ago by Jannis Leidel

Resolution: worksforme
Status: newclosed

There is already one at https://code.djangoproject.com/browser/django/trunk/django/utils/translation/__init__.py?rev=16405#L111

def welcome_translated(language):
    with translation.override(language):
        return translation.ugettext('welcome')

comment:2 Changed 5 years ago by Ralph Broenink

Didn't notice that there was one already. Does not seem to be a documented feature.

Is it an idea to also support it as a decorator?

comment:3 Changed 5 years ago by Jannis Leidel

Yeah, it's not documented yet, it should probably be mentioned on https://docs.djangoproject.com/en/dev/ref/utils/#module-django.utils.translation

I don't see much use in a decorator since that'd be evaluated at import time, making the variable override useless.

Note: See TracTickets for help on using tickets.
Back to Top