分配 css class 形成从 flask 传递到 jinja 的元素

assigning css class to form element passed from flask to jinja

我对 jinja / flask 很陌生,我正在我的 flask 应用程序中创建动态形式:

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

在神社模板中:

<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 
            &nbsp;
            <input type="checkbox" name="remember">Remember<br/ >
        </dd>

    </dl>
 </form>

我想将 class form-group 分配给 searchCity 输入框! 任何帮助将不胜感激谢谢

您应该能够像这样将变量传递到构造函数中

{{ form.searchCity(size=20, class_='searchCity') }}  

文档位于:

http://wtforms.readthedocs.io/en/latest/crash_course.html#rendering-fields

文档片段

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" />'

WTForms 2.1 中,我使用 extra_classes,就像下面的行:

1.第一种方式

{{ f.render_form_field(form.searchCity, extra_classes='ourClasses') }}

或者在你的情况下可能是这样的:

{{ form.searchCity, extra_classes='form-group' }}

我们也可以像下面第二种方式一样在我们的表单字段上使用 render_kw 属性:

2。第二种方式

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)

但我更愿意使用第一种方式。