Pyramid TranslationString 不适用于 json 渲染器 [英] Pyramid TranslationString not working on json renderer
问题描述
在我在金字塔应用程序中进行的测试中,我尝试通过 JSON 发送可翻译文本,但翻译无效.在文件的开头我导入了翻译字符串函数:
In a test I am doing in a pyramid application, I am trying to send a translatable text via JSON, but the translation is not working. At the beginning of the file I am importing the translation string function:
from pyramid.i18n import TranslationString as _
然后考虑以下代码:
@view_config(route_name='transtest', renderer='json')
def transtest_view(request):
return { 'myvar': _('temp-test', default='Temporary test', domain='myapp') }
但我得到的是:
{"myvar": "temp-test"}
请注意,如果我将渲染器更改为测试模板,我会执行以下操作:
Note that if I change the renderer to a test template I did as follows:
@view_config(route_name='transtest', renderer='../templates/transtest.pt')
...
然后文本被正确翻译(请注意,我已经初始化了目录,更新了它们,编译了它们等)
then the text gets translated correctly (note that I already initialized the catalogs, updated them, compiled them, etc.)
这让我觉得 TranslationString 类在json"渲染器中无法正常工作?如果是这样,我该如何通过 JSON 发送可翻译的字符串?
This made me think that the TranslationString class does not work right in a 'json' renderer? If so, how can I make to send a translatable string via JSON?
提前致谢
推荐答案
您需要明确地翻译您的消息字符串,使用 get_localizer()
和 Localizer.translate()
:
You need to explicitly translate your message string, using get_localizer()
and Localizer.translate()
:
from pyramid.i18n import get_localizer
@view_config(route_name='transtest', renderer='json')
def transtest_view(request):
message = _('temp-test', default='Temporary test', domain='myapp')
return {'myvar': get_localizer(request).translate(message)}
通常,模板会为您处理这些步骤,但对于 JSON,您需要自己完成这些步骤.
Normally, templates take care of these steps for you, but for JSON you'll need to do so yourself.
您可能想要定义一个 TranslationStringFactory
用于您的项目,并重用它来生成您的消息字符串.将以下内容添加到您的项目中:
You probably want to define a TranslationStringFactory
for your project, and reuse that to produce your message strings. Add the following to your project:
from pyramid.i18n import TranslationStringFactory
myapp_domain = TranslationStringFactory(domain='myapp')
然后使用:
from my.project import myapp_domain as _
# ....
message = _('temp-test', default='Temporary test')
这篇关于Pyramid TranslationString 不适用于 json 渲染器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!