BootStrap-Flask使用指南

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/

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容