问题
I am quite new to jinja / flask, I am creating dymnamic form in my flask app:
class CreateForm(FlaskForm):
searchCity = StringField('View forcast of city:', validators=[InputRequired("Please enter the city you want to check weather updates")])
count = IntegerField("Days")
submit = SubmitField("Submit")
form = CreateForm(request.form)
form.count.default = count
form.count.label = "Days" if count > 1 else "Day"
form.count.data = count
and in jinja template:
<form>
<dl>
<dd>{{ form.searchCity.label }} {{ form.searchCity(size=20) }}
for next {{ form.count(size=2) }} {{ form.count.label }}
<input type="submit" class="btn-primary" value="Submit" id="calculate" onclick="getWeatherForcaset(
document.getElementsByName('searchCity')[whole_number].value,
document.getElementsByName('count')[whole_number].value
);" >
</dd>
<dd>
<input type="checkbox" name="exactMatch" checked="checked">Exact Match
<input type="checkbox" name="remember">Remember<br/ >
</dd>
</dl>
</form>
I want to assign class form-group to searchCity inputbox !
any help would be greatly appreciated thanks
回答1:
You should be able to pass variables into the constructor like so
{{ form.searchCity(size=20, class_='searchCity') }}
Documentation is available at :
http://wtforms.readthedocs.io/en/latest/crash_course.html#rendering-fields
Doc Snippet
However, the real power comes from rendering the field with its call() method. By calling the field, you can provide keyword arguments, which will be injected as html attributes in the output:
form.content(style="width: 200px;", class_="bar")
<input class="bar" id="content" name="content" style="width: 200px;" type="text" value="foobar" />'
回答2:
In WTForms 2.1 I using extra_classes, like the line bellow:
1. The first way
{{ f.render_form_field(form.searchCity, extra_classes='ourClasses') }}
or maybe in your case just like this:
{{ form.searchCity, extra_classes='form-group' }}
We can also use the render_kw attribute on our form field like the second way below:
2. The second way
style={'class': 'form-group', 'style': 'we can also add another css style here'}
searchCity = StringField('View forcast of city:',
validators=[InputRequired("Please enter the city you want to check weather updates")],
render_kw=style)
But I would like more prefer to use the first way.
来源:https://stackoverflow.com/questions/45569640/assigning-css-class-to-form-element-passed-from-flask-to-jinja