Localization in Pyramid ZPT Chameleon Template

331 views Asked by At

I try to get string translations working in Pyramid with ZPT templates. I followed the Pyramid guide on internationalization and localization, i.e. 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 (i.e. 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?

2

There are 2 answers

1
romor On BEST ANSWER

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, e.g.:

<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.

0
tsauerwein On

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>