In my FLask app I use a Cookie to set the language.
Hence I'm able to call a route and render a template passing the languagecookie's value to the template and render it using conditional jinja IF statements in the HTML template.
I also use WTForms to build and render forms (eg contact form) in my templates
@app.route('/contact', methods=['GET'])
def contact():
languageCookie = request.cookies.get('language')
form = ContactForm()
return render_template('contact.html', language=languageCookie, ContactForm = form)
class ContactForm(FlaskForm):
Name = StringField('Naam',
validators=[InputRequired(message="Een naam is verplicht"),
Length(min=2, max=25, message="Minimum 2 en maximum 25 characters")],
render_kw={'class':'form-control g-color-black g-bg-white g-bg-white--focus g-brd-gray-light-v4 g-brd-primary--focus rounded-3 g-py-13 g-px-15','placeholder':'Naam'})
My questions is, would it be possible to alter the content within this WTForm class based on the value of the language cookie?
E.g. changing the field's message value in the validator, etc.
Already tried, didn't succeed since the cookie has no reference outside a route. What should be a better approach to have a WTForms class be language aware?
Many thanks in advance!
Here is a solution that I tested:
@app.route('/contact')
def contact():
languageCookie = request.cookies.get('language')
form = ContactForm(languageCookie)
return render_template('contact.html', language=languageCookie, ContactForm=form)
name_field = {
'language1': {
'label': 'label in language 1',
'required_message': 'required_message in language 1',
'length_message': 'length_message in language 1',
'placeholder': 'placeholder in language 1'
},
'language2': {
'label': 'label in language 2',
'required_message': 'required_message in language 2',
'length_message': 'length_message in language 2',
'placeholder': 'placeholder in language 2',
}
}
def ContactForm(language):
class Form(FlaskForm):
name = StringField(name_field[language]['label'],
validators=[
InputRequired(message=name_field[language]['required_message']),
Length(min=2, max=25, message=name_field[language]['length_message'])
],
render_kw={'class': 'classes', 'placeholder': name_field[language]['placeholder']})
return Form()
You create the actual form class and instantiate the class in one function, which is called every time the user views /contact
. I wouldn't recommend this though since you have to create a dictionary for each field which can become tedious.
If you want to have the same message displayed to users, but translated to their language, I would use flask-babel which handles translations for you. It's a bit more work initially but will make your life easier in the future. Here is a tutorial.
You can incorporate your cookie system by changing the get_locale function
@babel.localeselector
def get_locale():
return request.cookies.get('language')