我刚刚找到了一种方法,但我不确定它是不是最好的方法......无论如何,我混合了来自Mako i18n 配方的信息,简单形式的文档以及 Pylons 是如何做到的(pylons.decorators 中的 PylonsFormEncodeState ) 我想出了以下...
我订阅了这样的 NewRequest 事件:
config.add_subscriber("myproject.subscribers.add_localizer",
"pyramid.events.NewRequest")
然后定义add_localizer
:
from pyramid import i18n
from formencode import api as formencode_api
def add_localizer(event):
request = event.request
localizer = i18n.get_localizer(request)
if not hasattr(localizer, "old_translate"):
localizer.old_translate = localizer.translate # Backup the default method
request.localizer = localizer
request.translate = lambda x: localizer.translate(i18n.TranslationString(x))
# Set FormEncode language for this request
formencode_api.set_stdtranslation(languages=["it"]) # This should depend on the user's selection or whatever
def multiple_gettext(value):
# Try default translation first
t = localizer.old_translate(i18n.TranslationString(value))
if t == value:
# It looks like translation failed, let's try FormEncode
t = formencode_api._stdtrans(value)
return t
localizer.translate = multiple_gettext