Enable automatic translations with Mako
I recently discovered the new framework Pyramid. This blog will be used to share code snippets that I find interesting.
First up: Automatic translations with the Mako template engine. (thanks to the people in #pylons@freenode for helping me)
__init__.py:
Add this above main():
from pyramid.events import BeforeRender
from MyProject import helpers
def add_renderer_globals(event):
event['_'] = helpers._
In main(), add this:
config.add_subscriber(add_renderer_globals, BeforeRender)
helpers.py
Add helpers.py in the same directory as your __init__.py
from pyramid.i18n import TranslationStringFactory
from pyramid.i18n import get_localizer
# Translation:
tsf = TranslationStringFactory('MyProject')
def _(string, request):
localizer = get_localizer(request)
translated = localizer.translate(tsf(string))
return translated
In your Mako template:
Now you can use ${_(‘I want to translate this’, request)} to automatically translate what’s in _(‘here’, request). I didn’t find out how to eliminate the request, so if you know, please leave a comment.
Of course you will also need to run python setup.py extract_messages, init_catalog etc. and change the default locale (default_locale_name = something) in development.ini, for this to work.
As I said, I’m new to Pyramid, so I’m not sure if this is the best way of achieving automatic translations, but it works. Comments are appreciated!
