Flask-security and Bootstrap

最后都变了- 提交于 2019-12-05 08:55:53

The render_field_* functions accepts a class_ parameter, which will add HTML classes to the field. Add in bootstrap styling classes as you want.

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

And so on.

Flask-Security uses Flask-WTForms to render and validate forms. In Flask-Security 1.7.5, the default render_field_with_errors and render_field macros defined in "security/_macros.html" are

{% 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 %}

According to the Flask-WTForms 0.10 docs, both of the above macro functions accept ...

... keyword arguments that are forwarded to WTForm’s field function that renders the field for us. The keyword arguments will be inserted as HTML attributes.

Specifically, the lines {{ field(**kwargs)|safe }} pass the HTML escaped keyword arguments to the field function. Therefore, you can add classes,

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

and can also overwrite default HTML attributes,

{{ 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" ) }}

Additionally, you can define your own macros by modifying the macros above. For example, if you wanted to use Bootstrap alerts to render form validation errors, you could define the macro function 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 %}

Adding your own macro is pretty simple. For example, you can put custom macros in a "custom_macros.html" file within the templates directory and then load the functions into templates with

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

This way, it is easy to modify the macros to use different Bootstrap features.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!