Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 249
Ken Kinder Avatar asked Jun 02 '16 17:06

Ken Kinder


People also ask

What is the difference between Jinja and Jinja2?

from_string . Jinja 2 provides a Template class that can be used to do the same, but with optional additional configuration. Jinja 1 performed automatic conversion of bytes in a given encoding into unicode objects.

What is the Jinja2 delimiters for expressions to print to the template output?

The default Jinja delimiters are configured as follows: {% ... %} for Statements. {{ ... }} for Expressions to print to the template output.

Is Jinja only for HTML?

Additionally Jinja is a general purpose template engine and not only used for HTML/XML generation. For example you may generate LaTeX, emails, CSS, JavaScript, or configuration files.


1 Answers

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

like image 163
Bartlett Avatar answered Oct 10 '22 00:10

Bartlett