3

我知道我可以在 python shell 中运行以下代码:

import formencode
ne = formencode.validators.NotEmpty()
formencode.api.set_stdtranslation(languages=["it"])
try:
    ne.to_python("")
except formencode.api.Invalid, e:
    print str(e)

并打印

Inserire un valore

现在我如何在我的金字塔应用程序中使用带有 Formencode 的 pyramid_simpleform 获得相同的结果?

4

1 回答 1

4

我刚刚找到了一种方法,但我不确定它是不是最好的方法......无论如何,我混合了来自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
于 2011-10-24T21:47:03.737 回答