Django 模板变量(模型实例)翻译

Django template variable (model instance) translation

我的数据库中有一个带有 name CharField 的 Product 模型。有一个模板用于在页面上呈现 Product 模型的一个实例。在视图中,我正在传递给模板 product 变量,该变量是 Product 模型的过滤实例。在模板中,我需要根据现在呈现的 Product 个实例页面来翻译变量 {{ product.name }}。 阅读 Django 文档后:

To translate a template expression – say, accessing object attributes or using template filters – you need to bind the expression to a local variable for use within the translation block.

我决定使用下一个:

{% blocktrans with product_name=product.name%}{{product_name}}{% endblocktrans %}

在 django.po 文件中我得到:

msgid "%(product_name)s"

你能告诉我,我走对了吗? 如果这种方法只允许为一个 product.name 提供翻译,那么应该如何翻译其他 product 实例的 name 属性? 感谢您的关注!

不是这样的。

生成 .po 文件时,它不会通过您的数据库获取所有产品并为其名称创建 msgid

您可以使用django内置的翻译机制来翻译静态内容。

对于您要实现的目标,我认为 django-modeltranslation 之类的东西会很合适。