Django 懒惰与非懒惰翻译

例子

使用非延迟翻译时,字符串会被立即翻译。

>>> from django.utils.translation import activate, ugettext as _
>>> month = _("June")
>>> month
'June'
>>> activate('fr')
>>> _("June")
'juin'
>>> activate('de')
>>> _("June")
'Juni'
>>> month
'June'

使用懒惰时,只有在实际使用时才会进行翻译。

>>> from django.utils.translation import activate, ugettext_lazy as _
>>> month = _("June")
>>> month
<django.utils.functional.lazy.<locals>.__proxy__ object at 0x7f61cb805780>
>>> str(month)
'June'
>>> activate('fr')
>>> month
<django.utils.functional.lazy.<locals>.__proxy__ object at 0x7f61cb805780>
>>> "month: {}".format(month)
'month: juin'
>>> "month: %s" % month
'month: Juni'

在以下情况下,您必须使用延迟翻译:

  • _("some string")评估时可能无法激活翻译(未选择语言)

  • 某些字符串可能仅在启动时进行评估(例如,在模型和表单字段定义等类属性中)