Django中的“惰性翻译”方法的相关使用

WBOY
Release: 2016-06-06 11:13:22
Original
1239 people have browsed it

使用 django.utils.translation.gettext_lazy() 函数,使得其中的值只有在访问时才会被翻译,而不是在 gettext_lazy() 被调用时翻译。

例如:要翻译一个模型的 help_text,按以下进行:

from django.utils.translation import ugettext_lazy

class MyThing(models.Model):
  name = models.CharField(help_text=ugettext_lazy('This is the help text'))

Copy after login

在这个例子中, ugettext_lazy() 将字符串作为惰性参照存储,而不是实际翻译。 翻译工作将在字符串在字符串上下文中被用到时进行,比如在Django管理页面提交模板时。

在Python中,无论何处你要使用一个unicode 字符串(一个unicode 类型的对象),您都可以使用一个 ugettext_lazy() 调用的结果。 一个ugettext_lazy()对象并不知道如何把它自己转换成一个字节串。如果你尝试在一个需要字节串的地方使用它,事情将不会如你期待的那样。 同样,你也不能在一个字节串中使用一个 unicode 字符串。所以,这同常规的Python行为是一致的。 例如:

# This is fine: putting a unicode proxy into a unicode string.
u"Hello %s" % ugettext_lazy("people")

# This will not work, since you cannot insert a unicode object
# into a bytestring (nor can you insert our unicode proxy there)
"Hello %s" % ugettext_lazy("people")

Copy after login

如果你曾经见到到像"hello"这样的输出,你就可能在一个字节串中插入了ugettext_lazy()的结果。 在您的代码中,那是一个漏洞。

如果觉得 gettext_lazy 太过冗长,可以用 _ (下划线)作为别名,就像这样:

from django.utils.translation import ugettext_lazy as _

class MyThing(models.Model):
  name = models.CharField(help_text=_('This is the help text'))

Copy after login

在Django模型中总是无一例外的使用惰性翻译。 为了翻译,字段名和表名应该被标记。(否则的话,在管理界面中它们将不会被翻译) 这意味着在Meta类中显式地编写verbose_nane和verbose_name_plural选项,而不是依赖于Django默认的verbose_name和verbose_name_plural(通过检查model的类名得到)。

from django.utils.translation import ugettext_lazy as _

class MyThing(models.Model):
  name = models.CharField(_('name'), help_text=_('This is the help text'))
  class Meta:
    verbose_name = _('my thing')
    verbose_name_plural = _('mythings')

Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!