ugettext 和 ugettext_lazy

2022-01-18 00:00:00 python django internationalization

问题描述

您能解释一下 ugettextugettext_lazy 之间的主要区别吗?

Could you explain what principal difference between ugettext and ugettext_lazy?

当我尝试时

return HttpResponse(ugettext_lazy("Hello"))

我什么也没看到,但是

return HttpResponse(ugettext("Hello"))

正在工作.

为什么?


解决方案

ugettext 用于加载字符串的翻译现在.ugettext_lazy 返回一个最终可以变成字符串的对象.如果在设置正确的语言环境之前评估了 ugettext_lazy 调用,则需要这样做.

ugettext is used to load a translation of a string right now. ugettext_lazy returns an object that can eventually be turned into a string. You need that if the ugettext_lazy call is evaluated before the proper locale has been set.

ugettext_lazy 可用于使用 Unicode 对象的地方.仔细检查您的 HTML 输出,它可能如下所示:

ugettext_lazy can be used where you use a Unicode object. Double-check your HTML output, it might look like this:

<django.utils.functional...>

并且浏览器将其全部忽略为无法识别的标签.

and the browser is ignoring it all as an unrecognized tag.

在这种情况下,您不需要惰性翻译,因为您会立即使用该字符串.如果您出于某种原因确实想继续使用 ugettext_lazy,请尝试以下操作:

You don't need a lazy translation in this case, because you are immediately using the string. If you really want to continue with ugettext_lazy for some reason, try this:

return HttpResponse(ugettext_lazy("Hello").encode('utf-8'))

有关详细信息,请参阅文档.

See the docs for more information.

相关文章