Django模板:用HTML翻译文本块的最佳做法 [英] Django templates: Best practice for translating text block with HTML in it

查看:140
本文介绍了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.

有更好的选择吗? / p>

Are there any better alternatives?

推荐答案

文档


不可能混合模板{%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天全站免登陆