python - How to use _ in mako rendering template with i18n? -


now using pyramid framework , mako template engine. , want add i18n feature.

there no problem if write code:

myprj/templates/index.html  <h1>${_('home')}</h1> 

it can rightly read compiled .mo file , show translated message kinds of languages.

but if use this:

myprj/templates/show.html  ${_context.detail_panel(order)} 

and write code in file:

myprj/templates/_detail_panel_a.html  <h1>${_('detail')}</h1> 

it shows error:

traceback (most recent call last): ... file "/mypath/myprj/templates/_detail_panel_a.html", line 5, in render_body <h1>${_('\u934j\u29jd\u01ld\u9dk3')}</h1> makorenderingexception:  traceback (most recent call last): ... file "/mypath/myprj/templates/_detail_panel_a.html", line 5, in render_body <h1>${_('\u934j\u29jd\u01ld\u9dk3')}</h1> unboundlocalerror: local variable '_' referenced before assignment 

i registered _ event in way:

myprj/myprj/subscribers.py  def add_renderer_globals(event):     request = event['request']     event['_'] = request.translate     event['localizer'] = request.localizer 

and call in __init__.py file:

myprj/myprj/__init__.py  config.add_subscriber('myprj.subscribers.add_renderer_globals', 'pyramid.events.beforerender') 

i don't know why not work when using render template page. think if necessary define _ event not request.translate, render method.

but after check official document, don't know how do.

how do?

you should refer http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/templates/mako_i18n.html

it should complete translation. can see, should add tsf global variable (from line 11 onwards in resource above).

also might want check rendering of templates mako, since read placing mako placeholder html file. suggest resource: http://docs.pylonsproject.org/projects/pyramid_mako/en/latest/

note: if add html tags msg strings, use | n filter mako placeholders in ${ | n}.

check these out, happy if had further problems, implemented internationalization on pyramid app


Comments