代码之家  ›  专栏  ›  技术社区  ›  EspenG

烧瓶安全和引导

  •  5
  • EspenG  · 技术社区  · 9 年前

    如何使用Bootstrap设计Flask安全登录站点?html表单如下所示:

    <form action="{{ url_for_security('login') }}" method="POST" name="login_form">
      {{ login_user_form.hidden_tag() }}
      {{ render_field_with_errors(login_user_form.email) }}
      {{ render_field_with_errors(login_user_form.password) }}
      {{ render_field_with_errors(login_user_form.remember) }}
      {{ render_field(login_user_form.next) }}
      {{ render_field(login_user_form.submit) }}
    </form>
    

    Bootstrap已经实现,但我不知道如何编辑字段和提交按钮。。

    2 回复  |  直到 9 年前
        1
  •  11
  •   jumbopap    9 年前

    这个 render_field_* 函数接受 class_ 参数,它将向字段中添加HTML类。根据需要添加引导样式类。

    render_field_with_errors(login_user_form.email, class_="form-control") }}
    {{ render_field(login_user_form.submit, class_="btn btn-default") }}
    

    等等

        2
  •  6
  •   eric    9 年前

    Flask Security使用Flask WTForms呈现和验证表单。在Flask Security 1.7.5中,默认 render_field_with_errors render_field “security/_macros.html”中定义的宏是

    {% macro render_field_with_errors(field) %}
      <p>
        {{ field.label }} {{ field(**kwargs)|safe }}
        {% if field.errors %}
          <ul>
          {% for error in field.errors %}
            <li>{{ error }}</li>
          {% endfor %}
          </ul>
        {% endif %}
      </p>
    {% endmacro %}
    
    {% macro render_field(field) %}
      <p>{{ field(**kwargs)|safe }}</p>
    {% endmacro %}
    

    根据 Flask-WTForms 0.10 docs ,以上两个宏函数都接受。。。

    …转发给WTForms字段函数的关键字参数,该函数为我们呈现字段。关键字参数将作为HTML属性插入。

    具体地说,行{{field(**kwargs)|safe}}将HTML转义的关键字参数传递给field函数。因此,您可以添加类,

    {{ render_field_with_errors(login_user_form.email, class="form-control") }}
    

    并且还可以覆盖默认HTML属性,

    {{ render_field_with_errors(login_user_form.email, 
        class="form-control", type="email", placeholder="Enter email") }}
    {{ render_field(login_user_form.submit, class="btn btn-default", value="Submit" ) }}
    

    此外,您可以 定义自己的宏 通过修改上面的宏。例如,如果要使用Bootstrap警报来呈现表单验证错误,可以定义宏函数 render_field_with_bootstrap_errors

    {% macro render_field_with_bootstrap_errors(field) %}
      <p>
        {{ field.label }} {{ field(**kwargs)|safe }}
        {% if field.errors %}
          {% for error in field.errors %}
            <div class="alert alert-danger" role="alert">{{ error }}</div>
          {% endfor %}
        {% endif %}
      </p>
    {% endmacro %}
    

    添加自己的宏非常简单。例如,您可以将自定义宏放在模板目录中的“custom_macros.html”文件中,然后使用

    {% from "custom_macros.html" import render_field_with_bootstrap_errors %}
    

    这样,很容易修改宏以使用不同的Bootstrap功能。