Opened 13 years ago

Closed 13 years ago

Last modified 13 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 by Jannis Leidel, 13 years ago

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 by Ralph Broenink, 13 years ago

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 by Jannis Leidel, 13 years ago

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