python-babel / flask-babel

i18n and l10n support for Flask based on Babel and pytz
https://python-babel.github.io/flask-babel/
Other
432 stars 159 forks source link

Flash messages not localised when a variable is in string #198

Closed Porrumentzio closed 2 years ago

Porrumentzio commented 2 years ago

Hi, I'm Porru, the person in charge of LiberaForms. I have noticed that when a flash message has some variable in it, the string will not be localised. As a result, any flash message containing variables, marked with % or with .format(), is showed in the source language.

This happens using Flask v. 2.0.2, Flask-Babel v. 2.0.0 and Babel v. 2.9.1

Maybe we are doing something wrong or maybe this is a bug, so any help is appreciated to figure out what is this about

TkTech commented 2 years ago

Do you have a minimal reproduction example, or a link to your code?

Porrumentzio commented 2 years ago

Yes of course. You can see some of them here: https://gitlab.com/liberaforms/liberaforms/-/blob/main/liberaforms/views/form.py#L446 https://gitlab.com/liberaforms/liberaforms/-/blob/main/liberaforms/views/form.py#L398 https://gitlab.com/liberaforms/liberaforms/-/blob/main/liberaforms/views/form.py#L205

TkTech commented 2 years ago

Yes, you aren't using it correctly. What you're doing won't work in any translation tool.

    flash(_("This form is already shared with %s" % new_editor.email), 'warning')

This is telling it that the string you want translated is literally This form is already shared with editor@editor.com, rather than This form is already shared with %s. You pass the variables as arguments, and I also recommend you use named variables.

    flash(_("This form is already shared with %(email)s", email=new_editor.email), 'warning')
Porrumentzio commented 2 years ago

Thanks a lot! That worked well. I still have another doubt. How should we introduce parameters this way with ngettext, as it requires three arguments? For giving an example:

flash(ngettext("Deleted one answer",
               "Deleted %(num)s answers", num=total_answers,
               total_answers),
               'success')
TkTech commented 2 years ago

There is no difference. Pass your arguments as always.

ngettext("Deleted one answer", "Deleted %(num)s answers", total_answers, num=total_answers)