如何创建宏来清理WTForm错误检查?

时间:2016-09-11 02:03:51

标签: flask macros jinja2 wtforms flask-security

有没有更好的方法在我的表单字段中设置'has-error'类?我正在使用Flask和WTForms。以下代码有效,但非常重复。我尝试设置动态变量,例如{% set field + 'error' = 'has-error' %},但发现你无法在jinja中设置动态变量。

<form action="{{ url_for_security('login') }}" method="POST" name="login_user_form">
    {% if login_user_form.email.errors %}
        {% set email_error = 'has-error' %}
    {% endif %}
    {% if login_user_form.password.errors %}
        {% set password_error = 'has-error' %}
    {% endif %}

    <div class="form-group {{ email_error }}">
        {{ login_user_form.email(class='form-control input-lg', placeholder='Email', required='true') }}
        {% if login_user_form.email.errors %}
            {% for error in login_user_form.email.errors %}
                <span class="help-block">{{ error }}</span>
            {% endfor %}
        {% endif %}
    </div> <!-- / Email -->

    <div class="form-group signin-password {{ password_error }}">
        {{ login_user_form.password(class='form-control input-lg', placeholder='Password', required='true') }}
        {% if login_user_form.password.errors %}
            {% for error in login_user_form.password.errors %}
                <span class="help-block">{{ error }}</span>
            {% endfor %}
        {% endif %}
    </div> <!-- / Password -->

    <div class="form-actions">
        <input type="submit" value="Log In" class="btn btn-primary btn-block btn-lg">
    </div> <!-- / .form-actions -->
</form>

0 个答案:

没有答案