Django - Switch language setting for template rendering [duplicate]

江枫思渺然 提交于 2019-12-10 19:10:46

问题


Possible Duplicate:
Django switching, for a block of code, switch the language so translations are done in one language

Is there an easy way to get Django to switch language for a single template rendering operation?

In my case the user may trigger an event that will require to message a person that is not speaking the same language.

For instance - user is English speaker but invokes an action that messages a Spanish speaking person - thus I need to generate the outgoing content in Spanish language.

I am aware that it is possible by faking the Request and using RequestContext, however I would prefer a shorter/cleaner solution.


回答1:


Are you looking for something like the following:

from django.utils import translation
language_code = 'xx'
template_body = Template(some_text_var)
translation.activate(language_code)
r = template_body.render(context)
translation.deactivate()

For better code reuse, you can refactor this as a context manager.



来源:https://stackoverflow.com/questions/9853906/django-switch-language-setting-for-template-rendering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!