[Solved]-Can Django trans tags include HTML tags?

14👍

Can we include HTML tags inside the trans template tags?

No, we should not include HTML tags inside a trans template tag as you are doing in your 1st approach {% trans "Hold <em><strong>Ctrl</strong></em>" %} . This is a wrong approach

From the docs:

The {% trans %} template tag translates either a constant string
(enclosed in single or double quotes) or variable content.

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.

<title>{% trans "This is the title." %}</title> # example 1

<title>{% trans "myvar" noop %}</title>  # example 2

Solution-1: Using trans template tag

Instead of putting HTML code inside the trans tag, you can do something like below to get the desired result(though this is not the recommended approach).

{% trans "Hold" %} <em><strong>{% trans "Ctrl" %}</strong></em> # using trans tag

Solution-2: Using blocktrans tag instead

Better option is to use blocktrans template tag instead of trans tag to include the HTML tags.

the blocktrans tag allows you to mark complex sentences consisting of
literals and variable content for translation by making use of
placeholders:

You can then just do:

{% blocktrans %}
Hold <em><strong>Ctrl</strong></em>
{% endblocktrans %}

2👍

As Rahul said in his answer, one should not include HTML tags inside a trans template tag. However, according to Translating text blocks with Django .. what to do with the HTML? (which I just found), one can put HTML tags inside of blocktrans template tags instead. Thus I don’t have to do {% trans "Hold" %} <em><strong>{% trans "Ctrl" %}</strong></em>". I was unable to find such instructions in the Django 1.8 docs.

👤Daniel

Leave a comment