Opened 4 years ago

Closed 4 years ago

Last modified 4 years ago

#16690 closed New feature (worksforme)

Add translation.activate decorator/context manager

Reported by: ralphje 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 4 years ago by jezdez

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to worksforme
  • Status changed from new to closed

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 4 years ago by ralphje

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 4 years ago by jezdez

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