Ken Kinder
Ken Kinder

Reputation: 13140

With Jinja2 and Babel, how do I translate sentences containing HTML tags?

Suppose I have a Jinja2 template, and I'm using Flask-Babel to translate my project. For example:

<p>The <em>best</em> way of using the Internet is
to use <a href="{{ url_for('our_site') }}">our site</a>.</p>

So I have a sentence with a link and an emphasis. Suppose I then want to translate my sentence. The obvious way would be to use gettext() or the {% trans %} tag:

<p>{% trans %}The {% endtrans %} <em>{% trans %}best{% endtrans %}</em>
{% trans %}way of using the Internet is to use{% endtrans %}
<a href="{{ url_for('our_site') }}">{% trans %}our site{% endtrans %}</a>{% trans %}.{% endtrans %}</p>

Obviously the problem is that this breaks up the sentence into multiple fragments that don't translate well. This would result in the translator considering the string "The", "best", "way of using the Internet is to use", and "our site" as all separate strings, plus the punctuation. Of course, the translator will want to restructure the sentence, and choose what words to link and emphasize separately.

So in light of that, what's the solution? How do I have a sentence with tags in it that translates as one unit?

Upvotes: 12

Views: 4921

Answers (2)

turkus
turkus

Reputation: 4893

You can do that:

{% trans url=url_for('our_site') %}
<p>The <em>best</em> way of using the Internet is to use <a href="{{ url }}">our site</a>.</p>
{% endtrans %}

same with object nested variables (obj.site_name):

{% trans url=url_for('our_site'), site_name=obj.site_name %}
<p>The <em>best</em> way of using the Internet is
to use <a href="{{ url }}">our site</a>{{ site_name }}.</p>
{% endtrans %}

so you have to declare variables as the trans function params, otherwise trans won't work. To read more, please visit docs.

Upvotes: 3

Bartlett
Bartlett

Reputation: 934

You can use the gettext() and the safe filter

{{ gettext('The <em>best</em> solution') | safe }}

http://jinja.pocoo.org/docs/2.9/templates/#list-of-builtin-filters

Your translator would then be able to arrange the tags.

If you want to keep things a little simpler for the translator you could add a custom markdown filter and use that that add simple formatting within phrases, see here for an example https://gist.github.com/glombard/7554134

Upvotes: 3

Related Questions