简体   繁体   中英

Localization in Pyramid ZPT Chameleon Template

I try to get string translations working in Pyramid with ZPT templates. I followed the Pyramid guide on internationalization and localization, ie http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/i18n.html#chameleon-template-support-for-translation-strings .

However, when I add the line

<span>${some_translation_string}</span>

to my .pt template file I just get an assertion message from waitress:

NameError: some_translation_string

When I translate the string some_translation_string outside the ZPT templates (ie in the Python code of the view) it translates correctly. Thus, I think to have a valid compiled message catalog in place (though created manually due to missing Python3 support of babel/lingua).

I guess I misunderstand the way to insert localized strings in ZPT templates in general. It probably cannot be the same as for referencing variables?

As I understand now, translations within the ZPT template should look like this:

<span i18n:translate="">some_translation_string</h1>

If you omit the string identifier in i18n:translate the string itself is used for this.

Also you must add add the domain name in the template header, eg:

<html lang="en"
  xmlns:tal="http://xml.zope.org/namespaces/tal"
  xmlns:metal="http://xml.zope.org/namespaces/metal"
  xmlns:i18n="http://xml.zope.org/namespaces/i18n"
  i18n:domain="my_domain">

This information seems to be missing in the referenced Pyramid documentation.

For reference, to do translations for messages in your JavaScript code, I found this way handy:

In your view, add a TranslationStringFactory instance to the template parameters:

from translationstring import TranslationStringFactory

@view_config(route_name='site', renderer='templates/site.pt')
def form(request):
    ...
    return {'_': TranslationStringFactory('yourapp')}

Then in the template you can write:

<script type="text/javascript">
...
yourapp.i18n['error'] = '${_('Error')}';
yourapp.i18n['warning'] = '${_('Warning')}';

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM