美文网首页Python Web
BootStrap-Flask使用指南

BootStrap-Flask使用指南

作者: 北邮郭大宝 | 来源:发表于2020-01-10 09:24 被阅读0次

BootStrap-Flask是《Flask Web 开发实战》作者李辉维护的一个小工具,旨在提供Bootstrap和Flask集成的宏,可以快速构建自己的Web项目。这里简单介绍一下使用方法。

1.安装和初始化

$ pip install bootstrap-flask

​初始化和其他组件一样

from flask_bootstrap import Bootstrap
from flask import Flask
​
app = Flask(__name__)
​
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
​
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'secret string')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.root_path, 'data.db')

2. 宏定义

BootStrap-Flask主要提供的宏有如下几个:


1578409827787.jpg

下面挑几个常用的介绍一下,其他的可以参考其文档。

2.1 导航栏

使用方法:

render_nav_item(endpoint, text, badge='', use_li=False, **kwargs)

  • endpoint – The endpoint used to generate URL.
  • text – The text that will displayed on the item.
  • badge – Badge text.
  • use_li – Default to generate <a></a>, if set to True, it will generate <li><a></a></li>.
  • kwargs – Additional keyword arguments pass to url_for().

demo:

{% extends 'base.html' %}
{% from 'bootstrap/nav.html' import render_nav_item %}
​
{% block title %}  BootStrap-Flask nav {% endblock title%}
​
{% block content %}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="navbar-nav mr-auto">
        {{ render_nav_item('index', 'Home') }}
        {{ render_nav_item('breadcrumb', 'Breadcrumb') }}
        {{ render_nav_item('field', 'Field') }}
        {{ render_nav_item('form', 'Form') }}
        {{ render_nav_item('form_row', 'Form_Row') }}
        {{ render_nav_item('message', 'Flash') }}
        {{ render_nav_item('pager', 'Pager') }}
    </div>
</nav>
{% endblock content %}

效果:


1578567031904.jpg

2.2 表单1

使用方法:
render_form(form, action="", method="post", extra_classes=None, role="form", form_type="basic", horizontal_columns=('lg', 2, 10), enctype=None, button_map={}, id="", novalidate=False, render_kw={})

  • form – The form to output.
  • action – The URL to receive form data.
  • method – <form> method attribute.
  • extra_classes – The classes to add to the <form>.
  • role – <form> role attribute.
  • form_type – One of basic, inline or horizontal. See the Bootstrap docs for details on different form layouts.
  • horizontal_columns – When using the horizontal layout, layout forms like this. Must be a 3-tuple of (column-type, left-column-size, right-column-size).
  • enctype – <form> enctype attribute. If None, will automatically be set to multipart/form-data if a FileField is present in the form.
  • button_map – A dictionary, mapping button field names to names such as primary, danger or success. For example, {'submit': 'success'}. Buttons not found in the button_map will use the default type of button.
  • id – The <form> id attribute.
  • novalidate – Flag that decide whether add novalidate class in <form>.
  • render_kw – A dictionary, specifying custom attributes for the <form> tag.

demo:

class Login(FlaskForm):
    username = StringField('Name', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 128)])
    submit = SubmitField('Submit')
    
@app.route('/form')
def form():
    form = Login()
    return render_template('form.html', form=form)
{% extends 'base.html' %}
{% from 'bootstrap/form.html' import render_form %}
​
{% block title %}  BootStrap-Flask Form {% endblock title%}
​
{% block content %}
<div style="margin: 100px">
    <h3>render_form example</h3>
    <div >
        {{ render_form(form, button_map={'submit': 'success'}) }}
    </div>
</div>
{% endblock content %}

效果:


1578567431266.jpg

2.3 表单2

使用方法:
render_form_row(fields, row_class='form-row', col_class_default='col', col_map={})

  • fields – An iterable of fields to render in a row.

  • row_class – Class to apply to the div intended to represent the row, like form-row or row

  • col_class_default – The default class to apply to the div that represents a column if nothing more specific is said for the div column of the rendered field.

  • col_map – A dictionary, mapping field.name to a class definition that should be applied to the div column that contains the field. For example: col_map={'username': 'col-md-2'})

demo:

class Login2(FlaskForm):
    username = StringField('Name', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 128)])
    email = StringField('Email', validators=[DataRequired(), email()])
    remember = BooleanField('Remember', default=True)
    submit = SubmitField('Submit')
​
@app.route('/form_row')
def form_row():
    form = Login2()
    return render_template('form_row.html', form=form)
{% extends 'base.html' %}
{% from 'bootstrap/form.html' import render_form_row %}
​
{% block title %}  BootStrap-Flask  {% endblock title%}
​
{% block content %}
<div style="margin: 100px">
    <h3>render_form_row example</h3>
    <form method="post">
        {{ form.csrf_token() }}
        {{ render_form_row([form.username, form.password], col_map={'username': 'col-md-4'}) }}
        {{ render_form_row([form.email]) }}
        {{ render_form_row([form.remember]) }}
        {{ render_form_row([form.submit]) }}
</form>
</div>
{% endblock content %}

效果:


1578568397001.jpg

2.4 分页符

使用方法:
render_pager(pagination, fragment='', prev=('<span aria-hidden="true">←</span> Previous')|safe, next=('Next <span aria-hidden="true">→</span>')|safe, align='', **kwargs)

  • pagination – Pagination instance.
  • fragment – Add url fragment into link, such as #comment.
  • prev – Symbol/text to use for the “previous page” button.
  • next – Symbol/text to use for the “next page” button.
  • align – Can be ‘left’, ‘center’ or ‘right’, default to ‘left’.
  • kwargs – Additional arguments passed to url_for.

demo:

app.config['STUDENT_PER_PAGE'] = 5
​
class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(30))
​
@app.route('/pager')
def pager():
    page = request.args.get('page', 1, type=int)
    per_page = app.config['STUDENT_PER_PAGE']
    pagination = Student.query.order_by(Student.id.asc()).paginate(page, per_page=per_page)
    students = pagination.items
    return render_template('pager.html', pagination=pagination, students=students)
{% extends 'base.html' %}
{% from 'bootstrap/pagination.html' import render_pager %}
​
{% block title %}  BootStrap-Flask Pager {% endblock title%}
​
{% block content %}
<div style="margin: 100px">
    <h3>render_pager example</h3>
    <div>
        {% if students %}
            {% for student in students %}
                <h3 class="text-primary"><p>{{ student.username }}</p></h3>
            {% endfor %}
        {% endif %}
    </div>
    {{ render_pager(pagination, prev='上一页', next='下一页', align='center') }}
</div>
{% endblock content %}

效果:


1578568611135.jpg

3. 总结

总体使用还是比较方便的,主要是对于不想花过多时间投入到前端Web开发来说,是比较好的工具。详细的信息可以参阅其文档:https://bootstrap-flask.readthedocs.io/en/latest/

相关文章

网友评论

    本文标题:BootStrap-Flask使用指南

    本文链接:https://www.haomeiwen.com/subject/uihuactx.html