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?
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.
The default Jinja delimiters are configured as follows: {% ... %} for Statements. {{ ... }} for Expressions to print to the template output.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With