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

后端 未结 3 539
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 02:54

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

{% trans \"Please\" %}
    

        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 03:15

    From 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.

    Then under 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 in order to use MyApplicationName.
    {% endblocktrans %}
    

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

提交回复
热议问题