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

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</a> 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)