在 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/