Django 模板:翻译带有 HTML 的文本块的最佳实践 [英] Django templates: Best practice for translating text block with HTML in it

查看:34
本文介绍了Django 模板:翻译带有 HTML 的文本块的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Django templates, how would I translate a block that contains HTML? For example:

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

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

Splitting up translated strings allows me to change the HTML in the template at any time, but I guess it would make more sense to put it into a single translation string, like so:

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

但是 HTML 标记在翻译字符串中,即如果我想更改 HTML(例如,锚的 CSS 类),我必须重新翻译每种语言的字符串.

But then the HTML markup is in the translation string, i.e. if I wanted to change the HTML (e.g. CSS class for the anchor), I'd have to retranslate the string for each language.

有没有更好的选择?

推荐答案

来自 文档:

不能在 {% trans %} 内的字符串中混合模板变量.如果您的翻译需要带有变量(占位符)的字符串,请改用 {% blocktrans %}.

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 %}

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

This way your translated strings have the placeholders. In your case:

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

您需要在视图函数中生成 anchor 中的文本.这使它远离你的翻译字符串.

You will need to generate the text that goes in anchor in your view function. This keeps it out of your translated string.

这篇关于Django 模板:翻译带有 HTML 的文本块的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆