Django 模板中的 _() 或 {% trans %} ?
在 Django 模板中,您可以使用 {{ _("Hello World") }}
或 {% trans "Hello World" %}
来标记要翻译的字符串。在文档中,“官方”方法似乎是 {% trans %}
标签,但也提到了 _()
语法 一次。
这些方法有何不同(语法除外)以及为什么应该选择其中一种而不是另一种?
一个区别是,您显然不能将 {% trans %}
与标签和过滤器一起使用。但这是否意味着我可以在任何地方使用 _()
,例如 {{ _("String") }}
?与使用带有独立字符串的 {% trans "String" %}
和带有标签和过滤器的 _()
相比,它的工作原理和外观更加清晰和一致。
In Django templates, you can use either {{ _("Hello World") }}
or {% trans "Hello World" %}
to mark strings to be translated. In docs, the “official” approach seems to be the {% trans %}
tag, but the _()
syntax is mentioned too once.
How these approaches differ (except syntax) and why should be one preferable rather than the other?
One difference is that you obviously can't use {% trans %}
with tags and filters. But does that mean that I can just use _()
everywhere, like {{ _("String") }}
? It works and looks much cleaner and more consistent than using {% trans "String" %}
with standalone strings and _()
with tags and filters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所以从 Django 1.5 开始,技术上似乎没有什么区别。在两种情况下,模板引擎会在内部标记要翻译的变量(通过设置其
translate
属性):{% trans VAR %}
时(请参阅TranslateNode
),或者_(
并以)
结尾(请参阅变量.__init__
)。稍后,当变量被解析时,Django 会包装它如果看到
translate
属性,则使用ugettext
或pgettext
。然而,从源代码中可以看出,有一些灵活性考虑因素支持
{% trans %}
标签:{% trans "String" noop %}
,它将把要翻译的字符串放入 .po 文件中,但在渲染时不会实际翻译输出(变量上没有内部translate
属性,没有ugettext
调用) ;{% trans "May" context "verb" %}
;{% trans "String" as
。翻译后的字符串%}
* 从 Django 1.4 开始。
如果我遗漏了任何内容,请随时纠正我或发布更好的答案。
So it seems that there's technically no difference as of Django 1.5. Template engine internally marks a variable for translation (by setting its
translate
attribute) in two cases:{% trans VAR %}
(seeTranslateNode
), or_(
and ends with)
(seeVariable.__init__
).Later, when the variable is being resolved, Django wraps it with
ugettext
orpgettext
if it sees thetranslate
attribute.However, as can be seen from source code, there are some flexibility considerations in favor of
{% trans %}
tag:{% trans "String" noop %}
, which will put the string for translation into .po files, but won't actually translate the output when rendering (no internaltranslate
attribute on variable, nougettext
call);{% trans "May" context "verb" %}
;{% trans "String" as
.translated_string %}
* As of Django 1.4.
Please feel free to correct me or post a better answer in case I'm missing anything.
trans 模板标记调用 ugettext() 函数。在 Django 中,_() 是 ugettext() 的别名。
django 对此进行了介绍文档。
The trans template tag calls the ugettext() function. In Django _() is an alias to ugettext().
This is covered in the django docs.