Home > Back-end >  flask_babel and Jinja2 How to include HTML or placeholders in translatable text?
flask_babel and Jinja2 How to include HTML or placeholders in translatable text?

Time:11-27

In a basic Flask website meant to be multilanguage, I would like to apply a style on specific words or expressions. To handle the multilanguage, I use flask_babelex and tokenize.

from tokenize import u
from flask_babelex import gettext

page_title = gettext(u'The best potatoes in the world!')

In the template, I would have this: <h2>{{ page_title }}</h2> which would be rendered this way: <h2>The best potatoes in the world!</h2>

In order to apply the proper styling effect, I would like the word "potatoes" to be in a span.

<h2>The best <span>potatoes</span> in the world!</h2>

Including the span in the page_title definition string doesn't work. It seems to be sanitized and the html appears as part of the string instead of being interpreted. A simple javascipt function to target the word in the rendered page won't do as the word would change with a different language (patatas for example). I suppose a complex javascript function, containing placeholders and completed at rendered time could be created but... I hope there is an easier way to achieve this.

What is the best to either include HTML in the original string or to include placeholders to be replaced in the Jinja2 template or any other suggestion?

CodePudding user response:

You can mark the contents as | safe to avoid HTML being escaped:

{{ page_title | safe }}

Assuming you don't let the users insert content for other users that could work.

Another option is to use placeholders for the tags you want to insert, such as:

{{ _('The best %(start_tag)spotatoes%(end_tag)s in the world!', start_tag='<span>', end_tag='</span>') | safe }}
  • Related