开发者

How to set the language in render_to_string helper?

开发者 https://www.devze.com 2023-02-01 13:57 出处:网络
From a save signal in Django I want to send an e-mail. The language of the email should be set based on the content being saved (it has a lang flag). How can I pass that language to 开发者_JAVA百科Dja

From a save signal in Django I want to send an e-mail. The language of the email should be set based on the content being saved (it has a lang flag). How can I pass that language to 开发者_JAVA百科Djangos render_to_string helper? I can only find language settings for RequestContexts, and there is no request or user available here.

Sincerely Björn


Answer based on Django docs:

from django.template.loader import render_to_string
from django.utils import translation

(...)

cur_language = translation.get_language()
try:
    translation.activate(some_language)
    text = render_to_string('email-confirmation.html')
finally:
    translation.activate(cur_language)

And quoting the documentation (emphasis mine):

You can load a translation catalog, activate it and translate text to language of your choice, but remember to switch back to original language, as activating a translation catalog is done on per-thread basis and such change will affect code running in the same thread.


From the documentation I found this way nicer:

To help write more concise code, there is also a context manager django.utils.translation.override() that stores the current language on enter and restores it on exit. With it, the above example becomes:

from django.utils import translation

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


It appears as I can use translation.activate(some_lang) before every message I send. I'm not sure if this is efficient or not.

I see that it's possible to send a Context instance to render_to_string. If I can place the language setting in that context somehow, it would be nice.


you can pass a custom dictionnary to render_to_string

render_to_string(template_name, dictionary=None, context_instance=None)

the default context variable for LANGUAGES (seen in django/middlewares/context_processors.py) are :

context_extras['LANGUAGES'] = settings.LANGUAGES
context_extras['LANGUAGE_CODE'] = translation.get_language()
context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi()

so maybe setting the LANGUAGE_CODE is enough :

render_to_string('email-confirmation.html', {'LANGUAGE_CODE':'en'})

your template should look like this :

{% load i18n %}
{% trans "Welcome to our new webapp" %}

Of course you'll to deal with .po files but you should be aware of that (if not check this)

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消