Search code examples
pythonflaskjinja2python-babelflask-babel

Using links with babel in Jinja2


Currently I'm using Flask and Jinja2 in combination with Babel. So far everything is working great.

The only problem I'm facing is when using links in a translated text. Let's say we have the following in HTML:

<p>You can change this in your <a href="{{ url_for("settings") }}">settings</a>.</p>

How would I use this in combination with babel?

I had been thinking of the following code, but this gives issues when the order of words is not the same in the translated language.

<p>{{ _("You can change this in your ")<a href="{{ url_for("settings") }}">{{ _("settings")</a>.</p>

Another idea was to put the entire HTML into the string to be translated but then I cannot use string escaping anymore.

What is the preferred way to do this?


Solution

  • I was looking for a solution to this and came across this excellent page.

    You can add links by using the string substitution that is available for jinja2 variables. Here is an example:

    {{ _("You can change this in your %(open)ssettings%(close)s.", open='<a href="/user/%d">' % user_id, close='</a>')|safe }}
    

    Your .po file will then have an entry like this:

    msgid "You can change this in your %(open)ssettings%(close)s."
    msgstr ""