Django 模板 : Best practice for translating text block with HTML in it

标签 django internationalization django-templates gettext

在 Django 模板中,我如何翻译包含 HTML 的 block ?例如:

{% trans "Please" %}
    <a href="{% url login %}?next={{ currentUrlPath }}">
        {% trans "log in" %}
    </a>
{% trans "in order to use MyApplicationName." %}

拆分翻译后的字符串让我可以随时更改模板中的 HTML,但我想将其放入单个翻译字符串中更有意义,如下所示:

{% url login as loginUrl %}
{% blocktrans %}
    Please
    <a href="{{ loginUrl }}?next={{ currentUrlPath }}">
        log in
    </a>
    in order to use MyApplicationName.
{% endblocktrans %}

但是 HTML 标记在翻译字符串中,也就是说,如果我想更改 HTML(例如 anchor 的 CSS 类),我必须为每种语言重新翻译字符串。

有没有更好的选择?

最佳答案

来自 the docs :

It's not possible to mix a template variable inside a string within {% trans %}. If your translations require strings with variables (placeholders), use {% blocktrans %} instead.

然后在blocktrans下:

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. Examples:

{% blocktrans with article.price as amount %}
That will cost $ {{ amount }}.
{% endblocktrans %}

{% blocktrans with value|filter as myvar %}
This will have {{ myvar }} inside.
{% endblocktrans %}

这样,您翻译的字符串就有了占位符。在你的情况下:

{% blocktrans with login_object.anchor as anchor %}
    Please {{ anchor|safe }}log in</a> in order to use MyApplicationName.
{% endblocktrans %}

您需要在 View 函数中生成进入 anchor 的文本。这会将它排除在翻译后的字符串之外。

关于Django 模板 : Best practice for translating text block with HTML in it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4640084/

相关文章:

GWT国际化

jsf - JSF 应用程序中的动态语言环境切换?

Python 语法推理(为什么不像 .django 模板语法那样回退?)

python - 我们可以为 Python 初学者学习 Django 吗?

javascript - 如何使用 django-channels 2 处理消息?

python - django:添加用户弹出窗口。缺少字段(名字、姓氏)

html - 元标记 : title and description for both latin and non latin letter site

Django ModelChoiceField : how to iter through the instances in the template?

Django 教程第 2 部分模板——未反射(reflect) base_site.html 更改

python - 字典联合并对另一个字段求​​和