Search code examples
pythonflaskflask-wtformspython-babelflask-babel

flask babel in a jinja macro


I think I got babel translation working ok in my templates for simple strings like this:

<label class="control-label">{{_('Start')}}</label>

it translates well according to my messages.po

But now in my forms I'd like to use this macro most of the time :

{% macro render_field_with_errors(field) %}
<div class="form-group">
    {{ field.label }} {{ field(class_='form-control', **kwargs)|safe }}
    {% if field.errors %}
    <ul>
        {% for error in field.errors %}
        <li>{{ error }}</li>
        {% endfor %}
    </ul>
    {% endif %}
</div>
{% endmacro %}

and I'd love to have {{ field.label }} translated

So I changed my form class adding getttext() like below, updated my messages.pot, translated messages.po, removed the fuzzy, compiled.

class ProfileForm(Form):
    location = StringField(gettext('location'), validators=[DataRequired()])
    password = PasswordField(gettext('password'), validators=[DataRequired()])
    unit = SelectField(gettext('unit'), coerce=int, choices=[(1, 'kilometers / meters'), (2, 'miles / feet')])
    submit = SubmitField(gettext('Update'))

Fields unfortunately aren't translated, the rest in the page is. Am I missing something ? Obviously yes !


Solution

  • well the solution is to use lazy_gettext instead of gettext in the class ProfileForm(Form):

    lazy_gettext