Skip to main content
 首页 » 编程设计

python之如何在带有 i18n 的 mako 渲染模板中使用 _

2025年05月04日11lvdongjie

现在我正在使用 Pyramid 框架和 mako 模板引擎。并希望添加 i18n 功能。

如果我写这段代码没有问题:

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

可以正确读取编译后的.mo文件,并显示某些语言的翻译信息。

但是如果我这样使用它:

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

并在此文件中写入代码:

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

它显示了这个错误:

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 

我以这种方式注册了_事件:

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

并在__init__.py文件中调用:

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

我不知道为什么当我使用渲染模板页面时它不起作用。我认为如果有必要定义 _ 事件,不仅要定义 request.translate,还要定义诸如 render 方法之类的东西。

但是在我检查了 official document 之后,我不知道该怎么做。

怎么办?

请您参考如下方法:

你应该引用http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/templates/mako_i18n.html

它应该可以帮助您完成翻译。如您所见,您应该添加一个 tsf 全局变量(从上面资源中的第 11 行开始)。

您可能还想检查您使用 mako 呈现的模板,因为根据我的阅读,您正在将 mako 占位符放入 html 文件中。我建议使用此资源:http://docs.pylonsproject.org/projects/pyramid_mako/en/latest/

注意:如果您将 html 标签添加到您的 msg 字符串中,请使用 | n 过滤到你的 mako 占位符中,如 ${ | n}.

检查这些,如果您还有其他问题,我很乐意提供帮助,我刚刚在我的 Pyramid 应用程序上实现了国际化