Translate elements from list in Jinja2 template using Flask-Babel

445 Views Asked by At

I have a Jinja2 template that the menu items are defined in a Jinja2 list like this:

{% set nav = [
    ('Foo', 'user.foo'),
    ('Bar', 'user.bar'),
] %}

Later in the template I have a for loop:

{% for title, endpoint in nav %}
  {% if endpoint == request.endpoint %}
    <li class="active"><a href="{{ url_for(endpoint) }}">{{ title|title }}</a></li>
  {% else %}
    <li><a href="{{ url_for(endpoint) }}">{{ title|title }}</a></li>
  {% endif %}
{% endfor %}

How should I user {% trans %} or {{ gettext() }} in my example to properly translate the menu items? I tried with putting {% trans %} in the for loop, but didn't got any success. Is there a way to translate the list elements that are defined in the template?

1

There are 1 best solutions below

0
On BEST ANSWER

Just translate the menu:

{% set nav = [
    (_('Foo'), 'user.foo'),
    (_('Bar'), 'user.bar'),
] %}

The _(...) is a short alias of gettext(...).

In general, you should translate the text where it is defined, so you risk less to have mangled text, so missing translations.