ithelloworld
ithelloworld

Reputation: 2247

How to use _ in mako rendering template with i18n?

Now I am using pyramid framework and mako template engine. And want to add i18n feature.

There is no problem if I write this code:

myprj/templates/index.html

<h1>${_('Home')}</h1>

It can rightly read the compiled .mo file and show the translated message from some kinds of languages.

But if I use it like this:

myprj/templates/show.html

${_context.detail_panel(order)}

And write code in this file:

myprj/templates/_detail_panel_a.html

<h1>${_('Detail')}</h1>

It shows this 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 this way:

myprj/myprj/subscribers.py

def add_renderer_globals(event):
    request = event['request']
    event['_'] = request.translate
    event['localizer'] = request.localizer

And call it in __init__.py file:

myprj/myprj/__init__.py

config.add_subscriber('myprj.subscribers.add_renderer_globals', 'pyramid.events.BeforeRender')

I don't know why it is not work when I using render template page. I think if it necessary to define the _ event not only request.translate, but also something like render method.

But after I check the official document, I don't know how to do.

How to do?

Upvotes: 2

Views: 709

Answers (1)

eton_ceb
eton_ceb

Reputation: 779

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

It should help you complete translation. As you can see, you should add a tsf global variable (from line 11 onwards in the resource above).

Also you might want to check your rendering of templates with mako, since from what I read you are placing a mako placeholder into an html file. I suggest this resource: http://docs.pylonsproject.org/projects/pyramid_mako/en/latest/

Note: if you add html tags into your msg strings, use | n filter into your mako placeholders as in ${ | n}.

Check these out, I would be happy to help if you had further problems, I just implemented internationalization on my Pyramid app

Upvotes: 1

Related Questions