Jinja2 translation of links

2020-07-13 09:06发布

问题:

From a Jinja2 template, this is the rendered line I'm after (in English):

This is the <a href="roadmap.html">roadmap</a>

Translated in Dutch should result in:

Dit is de <a href="roadmap.html">planning</a>

This Jinja2 line gets me there -almost-

{{ _('This is the %(roadmap)s.', roadmap='<a href="roadmap.html">roadmap</a>'|safe) }}

Unfortunately, the word 'roadmap' is not translated.

What would be the Jinja2 way of accomplishing this? Splitting the link in roadmap1 and roadmap2? I hope for something more clever.

回答1:

These should work:

{{ _('This is the') }} <a href="roadmap.html">{{ _('roadmap') }}</a>

{{ _('This is the %(roadmap)s', roadmap=('<a href="roadmap.html">%s</a>' % _('roadmap'))|safe) }} 

Also, if you use webapp2, you might want to replace href="roadmap.html" with e.g. href="{{ uri_for('roadmap') }}"



回答2:

Here's a solution that will get you everything in a single translatable string. You usually don't want the link text ("roadmap") to be a separate translation item.

It works by extracting the opening and closing tag into variables. These must be marked as safe, since they contain HTML content that would otherwise be escaped.

{% trans link_start='<a href="roadmap.html">'|safe, link_end='</a>'|safe %}
This is the {{ link_start }} roadmap {{ link_end }}.
{% endtrans %}