Pyramid TranslationString not working on json renderer

江枫思渺然 提交于 2019-12-11 02:38:46

问题


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 _

Then consider the following code:

@view_config(route_name='transtest', renderer='json')
def transtest_view(request):
    return { 'myvar': _('temp-test', default='Temporary test', domain='myapp') }

But what I get is:

{"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.)

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?

Thanks in advance


回答1:


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)}

Normally, templates take care of these steps for you, but for JSON you'll need to do so yourself.

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')

then use:

from my.project import myapp_domain as _

# ....

message = _('temp-test', default='Temporary test')


来源:https://stackoverflow.com/questions/17768375/pyramid-translationstring-not-working-on-json-renderer

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