0

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?

Xosted
  • 321
  • 2
  • 15

1 Answers1

2

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 }}
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • Hello, thank you @MatsLindh for the answer. The first option doesn't work. I have tried already, the string and probably sanitized prior to be handed over to Jinja2. It is important that the string is in a variable passed to the template and not directly in the template. How to achieve this with your second suggestion? – Xosted Nov 26 '21 at 15:03
  • I simply tried to place it in a variable and use the method you indicated. The placeholders were replaced in the template by span tags. However, they again appear in the page as text rather than HTML code. So, so far, none of the options seems to work. – Xosted Nov 26 '21 at 15:19
  • Ok... I don't know why but I came back to my original code shown in the original post, I added the "safe" word and now it works... – Xosted Nov 26 '21 at 18:06