【问题标题】:Flask-security and Bootstrap烧瓶安全和引导
【发布时间】:2016-04-12 02:34:25
【问题描述】:

如何使用 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,但是我不知道如何编辑字段和提交按钮..

【问题讨论】:

    标签: python twitter-bootstrap flask flask-login flask-security


    【解决方案1】:

    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】:

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

      {% 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,以上两个宏函数都接受...

      ... 关键字参数被转发到 WTForm 的字段函数,为我们呈现字段。关键字参数将作为 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 功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-04
        • 2021-09-07
        • 2019-05-29
        • 1970-01-01
        • 2018-09-12
        • 2015-09-14
        • 2019-03-10
        • 1970-01-01
        相关资源
        最近更新 更多