Django-切换用于模板渲染的语言设置 [英] Django - Switch language setting for template rendering
问题描述
Possible Duplicate:
Django switching, for a block of code, switch the language so translations are done in one language
是否有一种简单的方法可以让Django为单个模板渲染操作切换语言?
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.
我知道可以通过伪造Request并使用RequestContext来实现,但是我希望使用更短/更干净的解决方案.
I am aware that it is possible by faking the Request and using RequestContext, however I would prefer a shorter/cleaner solution.
推荐答案
您是否正在寻找类似以下的内容:
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.
这篇关于Django-切换用于模板渲染的语言设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!