gettext – Flask-Babel如何在Jinja模板文件中使用翻译

在我的Flask应用程序中,在main.py文件中,我定义了:
from flaskext.babel import gettext
....
def somefun():
    return render_template('some.html',messages=messages)

在模板文件some.html中,我用过:

<input type='text' name='keywords' value='{{ keywords|default('') }}' placeholder='{{ gettext('Search...') }}' />

这给出错误

<input type='text' name='keywords' value='{{ keywords|default('') }}' placeholder='{{ gettext('Search...') }}' />
UndefinedError: 'gettext' is undefined

如何导入这个功能,让模板使用?

解决方法

不幸的是,这根本没有记载,但flask-babel透明地使用了 Jinja2’s i18n extension.这意味着认情况下,表达式的以下函数可用:_gettext,_ngettext和_.

还有可能使用模板标签

{% trans %}foo{% endtrans%}

{% trans num %}
There is {{ num }} object.
{% pluralize %}
There are {{ num }} objects.
{% endtrans %}

bug report about missing docs正在等待补丁;)

相关文章

在前一篇博客中我们介绍了加侧旋的乒乓球弧圈技术的模拟,本...
在近期conda的版本更新中,有可能会删除路径下的_sysconfigd...
本文主要展示了一些lambda表达式的使用示例,通过这些示例,...
本文通过对比Jax和Numpy计算Normalized Hamming Distance的过...
我们知道GPU加速在可并行化程度比较高的算法中,能够发挥出比...
Numpy这个库在Python编程中非常的常用,不仅在性能上补足了P...