Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed...

45
Flask-Bootstrap Release 3.3.7.1 May 16, 2017

Transcript of Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed...

Page 1: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-BootstrapRelease 3.3.7.1

May 16, 2017

Page 2: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,
Page 3: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Contents

1 Basic usage 31.1 Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.2.1 Available blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.2.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.3 Static resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Configuration 7

3 Macros 93.1 Fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.2 Google Analytics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.3 Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

4 WTForms support 134.1 Form macro reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

5 Flask-SQLAlchemy support 15

6 Flask-Nav support 176.1 The BootstrapRenderer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

6.1.1 Customizing the navbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

7 CDN support 19

8 FAQ 218.1 Why do I have undesired auto-escapes in my template output? . . . . . . . . . . . . . . . . . . . . . 218.2 How can I add custom javascript to the template? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218.3 Why is Bootstrap javascript not loading? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218.4 How do I add custom stuff to the header? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228.5 How do I add a footer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228.6 How do I serve the static files in deployment? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228.7 How do I use Bootstrap 2/3? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238.8 Where is FontAwesome? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238.9 Why are you shipping jQuery 1 instead of jQuery 2? . . . . . . . . . . . . . . . . . . . . . . . . . . 238.10 How can I use jQuery2 instead of jQuery1? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

9 Using Bootstrap 2 25

i

Page 4: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

9.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259.2 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

9.2.1 Flask-Bootstrap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

10 Flask-Bootstrap Changelog 2910.1 3.3.7.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2910.2 3.3.5.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2910.3 3.3.5.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2910.4 3.3.5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2910.5 3.3.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3010.6 3.3.4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3010.7 3.3.0.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3010.8 3.2.0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3010.9 3.1.0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3010.10 3.0.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3010.11 3.0.0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3010.12 2.3.2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3110.13 2.3.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3110.14 2.3.0-2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3110.15 2.2.2-1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3110.16 2.2.1-1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3110.17 2.1.1-2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3110.18 2.1.1-1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3110.19 2.1.0-1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

11 33

12 Installation 35

13 Getting started 37

14 A note on versioning 39

ii

Page 5: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

Flask-Bootstrap packages Bootstrap into an extension that mostly consists of a blueprint named ‘bootstrap’. It canalso create links to serve Bootstrap from a CDN.

Contents 1

Page 6: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

2 Contents

Page 7: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 1

Basic usage

To get started, the first step is to import and load the extension:

from flask import Flaskfrom flask_bootstrap import Bootstrap

def create_app():app = Flask(__name__)Bootstrap(app)

return app

# do something with app...

After loading, new templates are available to derive from in your templates.

Sample Application

If you want to have a look at a small sample application, try browsing it on github.

Templates

Creating a new Bootstrap-based template is simple:

{% extends "bootstrap/base.html" %}{% block title %}This is an example page{% endblock %}

{% block navbar %}<div class="navbar navbar-fixed-top">

<!-- ... --></div>

3

Page 8: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

{% endblock %}

{% block content %}<h1>Hello, Bootstrap</h1>

{% endblock %}

Everything you do in child templates is based on blocks. Some blocks (like title, navbar or content) are“convenience blocks”. Strictly speaking they would not be necessary, but are added to save typing effort.

A very powerful feature is Jinja2’s super() function. This gives you the option of amending blocks instead of replacingthem.

Available blocks

Block name Outer Block Purposedoc Outermost block.html doc Contains the complete content of the <html> tag.html_attribs doc Attributes for the HTML tag.head doc Contains the complete content of the <head> tag.body doc Contains the complete content of the <body> tag.body_attribs body Attributes for the Body Tag.title head Contains the complete content of the <title> tag.styles head Contains all CSS style <link> tags inside head.metas head Contains all <meta> tags inside head.navbar body An empty block directly above content.content body Convenience block inside the body. Put stuff here.scripts body Contains all <script> tags at the end of the body.

Examples

• Adding a custom CSS file:

{% block styles %}{{super()}}<link rel="stylesheet"

href="{{url_for('.static', filename='mystyle.css')}}">{% endblock %}

• Custom Javascript loaded before Bootstrap’s javascript code:

{% block scripts %}<script src="{{url_for('.static', filename='myscripts.js')}}"></script>{{super()}}{% endblock %}

• Adding a lang="en" attribute to the <html>-tag:

{% block html_attribs %} lang="en"{% endblock %}

4 Chapter 1. Basic usage

Page 9: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

Static resources

The url-endpoint bootstrap.static is available for refering to Bootstrap resources, but usually, this isn’t needed.A bit better is using the bootstrap_find_resource template filter, which will take CDN settings into account.

The current resource-system is described in detail on CDN support.

1.3. Static resources 5

Page 10: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

6 Chapter 1. Basic usage

Page 11: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 2

Configuration

There are a few configuration options used by Flask-Bootstrap, these are regular Flask Configuration variables (there’sa manual on these here).

Note: There’s a Flask extension available to aid the creation of Twelve-Factor-patterned apps in the form of Flask-Appconfig. It also handles other kinds of configuration setups and goes along well with Flask-Bootstrap.

Option De-fault

BOOTSTRAP_USE_MINIFIEDTrue Whether or not to use the minified versions of the css/js files.BOOTSTRAP_SERVE_LOCALFalseIf True, Bootstrap resources will be served from the local app instance every

time. See CDN support for details.BOOTSTRAP_LOCAL_SUBDOMAINNone Passes a subdomain parameter to the generated Blueprint. Useful when

serving assets locally from a different subdomain.BOOTSTRAP_CDN_FORCE_SSLTrue If a CDN resource url starts with //, prepend 'https:' to it.BOOTSTRAP_QUERYSTRING_REVVINGTrue If True, will append a querystring with the current version to all static resources

served locally. This ensures that upon upgrading Flask-Bootstrap, these resourcesare refreshed.

7

Page 12: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

8 Chapter 2. Configuration

Page 13: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 3

Macros

Flask-Bootstrap comes with macros to make your life easier. These need to be imported like in this example:

{% extends "bootstrap/base.html" %}{% import "bootstrap/wtf.html" as wtf %}

This would import the wtf.html macros with the name-prefix of wtf (these are discussed below at WTFormssupport).

In addition to the small macros on this page, broad support for other libraries is also available; see WTForms supportand Flask-SQLAlchemy support for details.

Fixes

Cross-browser fixes (specifically for Internet Explorer < 9) are usually included, but not shipped with Flask-Bootstrap.You can download html5shiv and Respond.js, put them in your applications static folder and include them like in thisexample:

{% import "bootstrap/fixes.html" as fixes %}{% block head %}

{{super()}}{{fixes.ie8()}}

{% endblock %}

While the scripts are not included, links to them on CDNs are, so if you do not use BOOTSTRAP_SERVE_LOCAL,they will work out of the box. See CDN support for more details on how CDN-delivery works with Flask-Bootstrap.

Google Analytics

The Google Analytics API has changed fairly quickly recently, currently analytics.js is best supported, using theuanalytics(id, options='auto') macro:

9

Page 14: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

{% import "bootstrap/google.html" as google %}

{% block scripts %}{{super()}}{{google.uanalytics('U-XXXX-YY')}}

{% endblock %}

It is possible to pass through options to the ga() js function call, for example to utilize the User ID feature:

{{google.uanalytics('U-XXXX-YY', {'userId': 'myUser'})}}

If you want the analytics account to be configurable from the outside, you can use something like this instead:

{{google.uanalytics(config['GOOGLE_ANALYTICS_ID'])}}

Note: Please make sure you at least pseudomize user ids properly.

The officially deprecated ga.js API support is also available supported through a similarly named macroanalytics(account):

{{google.analytics(account=config['GOOGLE_ANALYTICS_ID'])}}

Utilities

A few extra template macros are available in the bootstrap/utils.html file. Like the form macros, theseare intended to aid rapid application development, until they are replaced with custom solutions in more matureapplications.

flashed_messages(messages=None, container=True, transform=..., default_category=None, dismissi-ble=False)

Renders Flask’s flash() messages. Maps commonly used categories to the slightly uncommon bootstrap cssclasses (i.e. error -> danger).

Parameters

• messages – A list of messages. If not given, will use get_flashed_messages() toretrieve them.

• container – If true, will output a complete <div class="container"> element,otherwise just the messages each wrapped in a <div>.

• transform – A dictionary of mappings for categories. Will be looked up case-insensitively. Default maps all Python loglevel names to bootstrap CSS classes.

• default_category – If a category does not has a mapping in transform, it is passedthrough unchanged. If default_category is set, it is replaced with this instead.

• dismissible – If true, will output a button to close an alert. For fully functioning,dismissible alerts, you must use the alerts JavaScript plugin.

Note that for this functionality to work properly, flashing messages must be categorized with a valid bootstrap alertcategory (one of success, info, warning, danger).

Example:

10 Chapter 3. Macros

Page 15: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

flash('Operation failed', 'danger')

Versions of Flask-Bootstrap pre-3.3.5.7 did not escape the content of flashed_messages to allow HTML to beused. This behaviour has changed, the preferred way to utilize HTML inside messages now is by using the Markup-wrapper:

from flask import flashfrom markupsafe import Markup

# ...

flash(Markup('Flashed message with <b>bold</b> statements'), 'success')

user_name = '<b>ad username'flash(Markup('<u>You</u> are our favorite user, <i>'

+ user_name+ Markup('</i>!'),

'danger')

icon(type, extra_classes, **kwargs)Renders a Glyphicon in a <span> element.

Parameters

• messages – The short name for the icon, e.g. remove.

• extra_classes – A list of additional classes to add to the class attribute.

• kwargs – Additional html attributes.

form_button(url, content, method=’post’, class=’btn-link’, **kwargs)Renders a button/link wrapped in a form.

Parameters

• url – The endpoint to submit to.

• content – The inner contents of the button element.

• method – method-attribute of the surrounding form.

• class – class-attribute of the button element.

• kwargs – Extra html attributes for the button element.

A handy little method to create things like delete-buttons without using GET requests. An example:

{{form_button(url_for('remove_entry', id=entry_id),icon('remove') + ' Remove entry')}}

3.3. Utilities 11

Page 16: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

12 Chapter 3. Macros

Page 17: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 4

WTForms support

The bootstrap/wtf.html template contains macros to help you output forms quickly. Flask-WTF is not adependency of Flask-Bootstrap, however, and must be installed explicitly. The API of Flask-WTF has changed quitea bit over the last few versions, Flask-Bootstrap is currently developed for Flask-WTF version 0.9.2.

The most basic way is using them as an aid to create a form by hand:

<form class="form form-horizontal" method="post" role="form">{{ form.hidden_tag() }}{{ wtf.form_errors(form, hiddens="only") }}

{{ wtf.form_field(form.field1) }}{{ wtf.form_field(form.field2) }}

</form>

However, often you just want to get a form done quickly and have no need for intense fine-tuning:

{{ wtf.quick_form(form) }}

Form macro reference

quick_form(form, action=”.”, method=”post”, extra_classes=None, role=”form”, form_type=”basic”,horizontal_columns=(‘lg’, 2, 10), enctype=None, button_map={}, id=”“)

Outputs Bootstrap-markup for a complete Flask-WTF form.

Parameters

• form – The form to output.

• method – <form> method attribute.

• extra_classes – The classes to add to the <form>.

• role – <form> role attribute.

13

Page 18: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

• form_type – One of basic, inline or horizontal. See the Bootstrap docs fordetails on different form layouts.

• horizontal_columns – When using the horizontal layout, layout forms like this. Mustbe a 3-tuple of (column-type, left-column-size, right-colum-size).

• enctype – <form> enctype attribute. If None, will automatically be set tomultipart/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. Buttons not found in the button_map will use the defaulttype of button.

• id – The <form> id attribute.

form_errors(form, hiddens=True)Renders paragraphs containing form error messages. This is usually only used to output hidden field form errors,as others are attached to the form fields.

Parameters

• form – Form, who’s errors should be rendered.

• hiddens – If True, render errors of hidden fields as well. If 'only', render only these.

form_field(field, form_type=”basic”, horizontal_columns=(‘lg’, 2, 10), button_map={})Renders a single form-field with surrounding elements. Used mainly by quick_form.

14 Chapter 4. WTForms support

Page 19: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 5

Flask-SQLAlchemy support

Flask-SQLAlchemy supports pagination through its paginate(), which will return a Pagination object. Thesecan automatically rendered through the render_pagination macro:

{% from "bootstrap/pagination.html" import render_pagination %}

{# ... #}

{{render_pagination(query_results)}}

render_pagination(pagination, endpoint=None, prev=’«’, next=’»’, ellipses=’. . . ’, size=None, args={},**kwargs)

Renders a pager for query pagination.

Parameters

• pagination – Pagination instance.

• endpoint – Which endpoint to call when a page number is clicked. url_for() will becalled with the given endpoint and a single parameter, page. If None, uses the requestscurrent endpoint.

• prev – Symbol/text to use for the “previous page” button. If None, the button will behidden.

• next – Symbol/text to use for the “previous next” button. If None, the button will behidden.

• ellipses – Symbol/text to use to indicate that pages have been skipped. If None, noindicator will be printed.

• size – Can be ‘sm’ or ‘lg’ for smaller/larger pagination.

• args – Additional arguments passed to url_for(). If endpoint is None, uses argsand view_args

• kwargs – Extra attributes for the <ul>-element.

15

Page 20: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

16 Chapter 5. Flask-SQLAlchemy support

Page 21: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 6

Flask-Nav support

The Flask-Nav extension allows easily creating navigational structures and Flask-Bootstrap ships with a Bootstrap-compatible renderer for these. Upon initializing an application, Flask-Bootstrap will register the Bootstrap renderer asthe default.

Rendering a navbar “just works”, for example

{% block navbar %}{{nav.mynavbar.render()}}{% endblock %}

will automatically emit Bootstrap-compatible HTML. A minimal example to generate a working navbar would be:

from flask_nav import Navfrom flask_nav.elements import Navbar, View

nav = Nav()

@nav.navigation()def mynavbar():

return Navbar('mysite',View('Home', 'index'),

)

# ...

nav.init_app(app)

See the sample application for a more detailed example on navigation.

17

Page 22: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

The BootstrapRenderer

The renderer for Bootstrap-specific HTML (available as flask_bootstrap.nav.BootstrapRenderer) hasa few specific features. Namely, the title attribute of any Navbar can also be a Link or View.

The title, if not None, will be rendered using the brand classes (see the Bootstrap docs for details) and if it has aget_url method, the return value of it will be the link for the brand text.

Customizing the navbar

To modify the output of the BootstrapRenderer, it is possible to subclass it and register the resulting child classas another renderer. See the Flask-Nav documentation for more information about that topic.

18 Chapter 6. Flask-Nav support

Page 23: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 7

CDN support

Flask-Bootstrap supports delivery via CDN or local resources, configurable at runtime. Upon initialization, Flask-Bootstrap will store a dictionary on your app named yourapp.extensions['bootstrap']['cdns'], whichmaps names to CDN instances.

You can use bootstrap_find_resource() in your templates as well when using other resources that may beavailable on CDNs. CDNs can be added by adding new entries to the dictionary mention above.

19

Page 24: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

20 Chapter 7. CDN support

Page 25: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 8

FAQ

Why do I have undesired auto-escapes in my template output?

Make sure your templates end in .htm, .html, .xml or .xhtml. Flask sets the Jinja2-autoescape mode dependingon the template file extension (see this StackOverflow question for more information).

General convention in Flask applications is to name your HTML-templates .html though.

How can I add custom javascript to the template?

Use Jinja2’s super in conjunction with the scripts block. The super-function adds the contents of a block from theparent template, that way you can even decide if you want to include it before or after jQuery/bootstrap. Example:

{% block scripts %}{{super()}}<script src="my_app_code.js">

{% endblock %}

Why is Bootstrap javascript not loading?

An easy-to-miss quirk are the block names: While there is a block named body, it usually is not the one you want toreplace, use content instead. Currently, javascript is loaded at the end of the <body> tag by default ).

Available blocks has more details.

21

Page 26: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

How do I add custom stuff to the header?

A question that often pops up is how to add custom things to the <head> element, like <link>-tags or favicons.This is also easily achieved using the super function:

{% block head %}{{super()}}<link rel="icon" type="image/png" href="http://example.com/myicon.png">{% endblock %}

This will add the desired content just above the closing </head> tag. Another way for larger projects is creating anew base template and adding the required blocks yourself:

{% block head %}{{super()}}{% block favicon %}<!-- default favicon could go here -->{% endblock %}{% block feeds %}{% endblock %}{% endblock %}

A child template of this base template can then use these blocks to specify a custom feed or favicon.

How do I add a footer?

The super() function can also be used to extend any block that is already defined. It is usually a good idea to createanother derived base template for certain layouts. An example with-footer.html:

{% extends "bootstrap/base.html" %}

{%- block content %}{{super()}}{%- block footer %}<footer>&copy; 2016 Awesome, Inc.</footer>{%- endblock footer %}{%- endblock content %}

The footer-block can be overriden in all templates that extend from with-footer.html.

How do I serve the static files in deployment?

Flask-Bootstrap is not special in the sense that it simply adds a blueprint named bootstrap. The static files mapto a specific URL-prefix (per default static/bootstrap) and are served from a specific directory found in yourvirtualenv installation (e.g. lib/python2.7/site- packages/flask_bootstrap/static), so a tradi-tional setup would be setting up your webserver to serve this address from the mentioned directory.

A more elegant approach is having a cache in front of the WSGI server that respects Cache-Control headers.Per default, Flask will serve static files with an expiration time of 12 hours (you can change this value using theSEND_FILE_MAX_AGE_DEFAULT), which should be sufficient.

For this approach nginx (or, if you prefer, Varnish) or their cloud-service based equivalents should suffice. Flask-Bootstrap 2.3.2.2 supports this by offering querystring revving (see BOOTSTRAP_QUERYSTRING_REVVING) toensure newer Bootstrap versions are served when you upgrade Flask-Bootstrap.

22 Chapter 8. FAQ

Page 27: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

How do I use Bootstrap 2/3?

The current major stable version of Bootstrap is 3, which unfortunately is backwards incompatible with Bootstrap 2.Flask-Bootstrap is maintained for the latest version of Bootstrap 2 (although you should not expect new features, onlybug fixes) and, of course, Bootstrap 3.

By installing Flask-Bootstrap, you will always get the latest version, which is Bootstrap 3. To install (or keep) Flask-Bootstrap 2, you will have to specify the version in your setup.py or requirements.txt like this:

# other stuff in setup.py# ...install_requires=['flask-bootstrap<3', 'another_package']# ...

It’s not a bad idea to pin to a specific Flask-Bootstrap (e.g. 'flask- bootstrap==2.3.2.2' to avoid surprisesin production).

See the Using Bootstrap 2 documentation for details.

Where is FontAwesome?

Versions of Flask-Bootstrap using Bootstrap 2 included FontAwesome, this is no longer the case for Flask-Bootstrap3 and higher.

Originally, Bootstrap did come only with image-based icons that did not scale well, FontAwesome fixed this byproviding vector-based replacements, as well as additional icons. However, starting with Bootstrap 3 icons wereincluded as a font again, for this reason FontAwesome was dropped from the extension to simplify things.

Today, FontAwesome is not the only choice, a comparison of available alternatives is available on the web.

If you still want to use FontAwesome, it’s easy to include it by adding it to the styles block inside your template derivedbase template:

{% block styles -%}{{super()}}<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel=→˓"stylesheet">{% endblock styles %}

Why are you shipping jQuery 1 instead of jQuery 2?

As of this writing (July 2014), there are two key differences between jQuery 1 and 2: Version 1 supports IE6-8 whileversion 2 drops the support for these old versions in exchange for a smaller memory footprint and a few performancegains. At least 20% of the browser landscape (source: NetMarketShare) still consists of browsers not supported byjQuery 2.

Unless you have specialized needs, the advantages of jQuery 2 still do not outweigh the disadvantages of not supportinga fifth of the market. In the end, Bootstrap and jQuery both aim at abstracting away difficult to handle quirks whenbuilding sites and this goal is currently better served with the wide support of jQuery1.

8.7. How do I use Bootstrap 2/3? 23

Page 28: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

How can I use jQuery2 instead of jQuery1?

You can use Flask-Bootstrap’s CDN support to enable loading these resources from a different source:

from flask_bootstrap import WebCDNapp.extensions['bootstrap']['cdns']['jquery'] = WebCDN(

'//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/')

This will load jquery.js or whatever is required from the WebCDN specified. If you prefer to ship your own localversion of jQuery, you can similarly use the following snippet:

from flask_bootstrap import StaticCDNapp.extensions['bootstrap']['cdns']['jquery'] = StaticCDN()

Note that in this case you need to download a suitable jquery.js and/or jquery.min.js and put it into yourapps static-folder.

All of the above setups will cause the BOOTSTRAP_SERVE_LOCAL-option to be ignored for jQuery as well. If youneed a more complicated setup support the option, have a look at the source of init_app and the docs of CDNsupport.

24 Chapter 8. FAQ

Page 29: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 9

Using Bootstrap 2

The current major stable version of Bootstrap is 3, which is backwards incompatible with Bootstrap 2. Besides version3, Flask-Bootstrap is maintained for the latest version of Bootstrap 2 (although you should not expect new features,only bug fixes).

Installation

By installing Flask-Bootstrap, you will always get the latest version, which is Bootstrap 3. To install (or keep) Flask-Bootstrap 2, you will have to specify the version in your setup.py or requirements.txt similiar to this:

# other stuff in setup.py...install_requires=['flask-bootstrap<3', 'another_package']

It’s not a bad idea to pin to a specific Flask-Bootstrap version (e.g. 'flask-bootstrap==2.3.2.2' to avoidsurprises in production).

Documentation

Before version 3, Flask-Bootstrap only had a README file as documentation. You can find the full file below.

You can also find previous version tags on github. To have a look at the code or sample app for major version 2, takea look at 2.3.2.2.

Flask-Bootstrap

Flask-Bootstrap packages Bootstrap into an extension that mostly consists of a blueprint named ‘bootstrap’. It canalso create links to serve Bootstrap from a CDN.

25

Page 30: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

Usage

Here is an example:

from flask_bootstrap import Bootstrap

[...]

Bootstrap(app)

This makes some new templates available, mainly bootstrap_base.html and bootstrap_responsive.html. These are blank pages that include all bootstrap resources, and have predefined blocks where you can put yourcontent. The core block to alter is body_content, otherwise see the source of the template for more possiblities.

The url-endpoint bootstrap.static is available for refering to Bootstrap resources, but usually, this isn’t needed.A bit better is using the bootstrap_find_resource template filter, which will CDN settings into account.

Macros

A few macros are available to make your life easier. These need to be imported (I recommend create your own“base.html” template that extends one of the bootstrap base templates first and including the the macros there).

An example “base.html”:

{% extends "bootstrap_responsive.html" %}{% import "bootstrap_wtf.html" as wtf %}

Forms

The bootstrap_wtf template contains macros to help you output forms quickly. The most basic way is using themas an aid to create a form by hand:

<form class="form form-horizontal" method="post">{{ form.hidden_tag() }}{{ wtf.form_errors(form, "only") }}

{{ wtf.horizontal_field(form.field1) }}{{ wtf.horizontal_field(form.field2) }}

<div class="form-actions"><button name="action_save" type="submit" class="btn btn-primary">Save changes</

→˓button></div>

</form>

However, often you just want to get a form done quickly and have no need for intense fine-tuning:

{{ wtf.quick_form(form) }}

Configuration options

There are a few configuration options used by the templates:

26 Chapter 9. Using Bootstrap 2

Page 31: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

Option DefaultBOOTSTRAP_USE_MINIFIEDTrue Whether or not to use the minified versions of the css/js files.BOOTSTRAP_JQUERY_VERSION'1' This version of jQuery is included in the template via Google CDN.

Also honors BOOTSTRAP_USE_MINIFIED. Set this to None tonot include jQuery at all. Note that non-minified Bootstrapresources are sometimes missing on bootstrapcdn, so it is best not touse it without turning on BOOTSTRAP_USE_MINIFIED.

BOOTSTRAP_HTML5_SHIMTrue Include the default IE-fixes that are usually included when usingbootstrap.

BOOTSTRAP_GOOGLE_ANALYTICS_ACCOUNTNone If set, include Google Analytics boilerplate using this account.BOOTSTRAP_USE_CDNFalse If True, Bootstrap resources will no be served from the local app

instance, but will use a Content Delivery Network instead(configured by BOOTSTRAP_CDN_BASEURL).

BOOTSTRAP_CDN_BASEURLA dictionary set upwith URLs tocdnjs.com.

The URLs to which Bootstrap and other filenames are appendedwhen using a CDN.

BOOTSTRAP_CDN_PREFER_SSLTrue If the BOOTSTRAP_CDN_BASEURL starts with //, prepend'https:' to it.

BOOTSTRAP_CUSTOM_CSSFalse If True, no Bootstrap CSS files will be loaded. Use this if youcompile a custom css file that already includes bootstrap.

BOOTSTRAP_QUERYSTRING_REVVINGTrue If True, will apppend a querystring with the current version to allstatic resources served locally. This ensures that upon upgradingFlask-Bootstrap, these resources are refreshed.

Installation

Either install from github using pip or from PyPI.

A note on versioning

Flask-Bootstrap tries to keep some track of Bootstrap’s releases. Versioning is usually in the form of Bootstrapversion - Flask-Bootstrap iteration. For example, a version of 2.0.3-2 bundles Bootstrap version2.0.3 and is the second release of Flask-Bootstrap containing that version.

If you need to rely on your templates not changing, simply pin the version in your setup.py.

FAQ

1. Why do I have undesired auto-escapes in my template output?

Make sure your templates end in .htm, .html, .xml or .xhtml. Flask sets the Jinja2-autoescape modedepending on the template file extension (see this StackOverflow question for more information).

General convention in Flask applications is to name your HTML-templates .html though.

2. How can I add custom javascript to the template?

Use Jinja2’s super() in conjunction with the bootstrap_js_bottom block. The super-function adds thecontents of a block from the parent template, that way you can even decide if you want to include it before orafter jQuery/bootstrap. Example:

{% block bootstrap_js_bottom %}{{super()}}

9.2. Documentation 27

Page 32: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

<script src="my_app_code.js">{% endblock %}

3. How do I serve the static files in deployment?

Flask-Bootstrap is not special in the sense that it simply adds a blueprint named bootstrap. The static filesmap to a specific URL-prefix (per default static/bootstrap) and are served from a specific directoryfound in your virtualenv installation (e.g. lib/python2.7/site-packages/flask_bootstrap/static), so a traditional setup would be setting up your webserver to serve this address from the mentioneddirectory.

A more elegant approach is having a cache in front of the WSGI server that respects Cache-Control headers.Per default, Flask will serve static files with an expiration time of 12 hours (you can change this value using theSEND_FILE_MAX_AGE_DEFAULT), which should be sufficient.

For this approach nginx (or, if you prefer, Varnish) or their cloud-service based equivalents should suffice. Flask-Bootstrap 2.3.2.2 supports this by offering querystring revving (see BOOTSTRAP_QUERYSTRING_REVVING)to ensure newer Bootstrap versions are served when you upgrade Flask-Bootstrap.

CHANGES

See Flask-Bootstrap Changelog for changes including version 2.

28 Chapter 9. Using Bootstrap 2

Page 33: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 10

Flask-Bootstrap Changelog

The following changes are not backwards compatible or major new features (bugfixes or new upstream releases arenot explicitly listed):

3.3.7.0

• Most likely to be the last major Bootstrap 3 release (see https://github.com/twbs/bootstrap/issues/20631). Makesure you pin Flask-Bootstrap’s version to <4 to avoid inadvertent updates.

3.3.5.7

• IE-specific meta information and viewport meta tags have been added to the base template.

• The flashed messages are no longer considered “safe”, which means HTML-markup will be escaped. Seeflashed_messages() for more information.

• The title block now contains an empty-by-default title variable.

3.3.5.3

• Support for Flask-Nav added: Flask-Nav support.

• The sample application has been rewritten to finally resemble a somewhat educative piece of code.

3.3.5.2

• action finally settled on "".

29

Page 34: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

3.3.5.1

• The action default value of quick_form() changed to ..

• An enctype value of quick_form(), which is the default, will automatically add the correct type if aFileField is present.

• The main bootstrap css file is no longer linked for just media="screen".

3.3.4.1

• Google Analytics API updated; the legacy API is still available.

• Flashed-message categories are now translated to bootstrap-y categories.

3.3.0.2

• New macro for pagination added (see Flask-SQLAlchemy support).

• New utils.html macro package added, includes message flashing, form-wrapped buttons and icons.

• A class required is added to wrappers when using quick_form().

3.2.0.1

• JQuery major version switched from 2 to 1. Detailed information on this change can be found in the FAQ.

3.1.0.1

• JQuery version increased to 2.1.0, html5shiv to 3.7 and respond.js to 1.4.2.

3.0.2.1

• Default action for forms changed from ”.” to nothing.

3.0.0.1

• New major upstream release (backwards incompatible!).

• Sphinx-based Documentation instead of README-file.

• No more SAMPLE_PROJECT, a new sample app has been provided.

• A lot of options are gone, their features being made obsolete, removed or integrated into other parts of theextension.

• A new CDN system replaced the old loading system.

30 Chapter 10. Flask-Bootstrap Changelog

Page 35: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

• FontAwesome has been removed in favor of Glyphicons (which now comes as a real font as well).

2.3.2.2

• html5-shim is loaded using a protocol-relative URL

• Rendering of RadioField changed (see sample app).

2.3.2.1

• Slight change in versioning (dot instead of hyphen for the Flask-Bootstrap release).

2.3.0-2

• Switched the CDN to cdnjs because netdna keeps changing files around too much.

• Introduced BOOTSTRAP_CUSTOM_CSS option.

2.2.2-1

• FontAwesome now version 3.0 instead of 2.0.

• The navbar()-macro is gone. It was accidentally committed and never did anything useful, so this hopefullywon’t concern anyone.

2.2.1-1

• FontAwesome is now supported as well, can also be loaded from bootstrapCDN. SetBOOTSTRAP_FONTAWESOME to True to enable it.

• BOOTSTRAP_CDN_BASEURL is now a dictionary for multiple CDNs (i.e. Bootstrap, FontAwesome can usedifferent base URLs). This will break any code that relied on setting BOOTSTRAP_CDN_BASEURL.

2.1.1-2

• There is no longer a self.app on Flask-Bootstrap. The extension can be shared by any number of applicationsusing init_app() (though the old __init__() signature is kept for backward compatibiliy).

2.1.1-1

• WTForms generated HTML code is now considered safe. This allows Flask-WTF’s RecaptchaField towork with quick_form.

10.12. 2.3.2.2 31

Page 36: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

2.1.0-1

• New upstream release: 2.1.0.

• Changed the default version of jQuery from 1.7.2 to just 1. This means that the latest 1.x.x version of jQuerywill be pulled.

32 Chapter 10. Flask-Bootstrap Changelog

Page 37: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 11

http://flask-bootstrap-zh.readthedocs.io/zh/latest/

https://github.com/lihuii/flask-bootstrap-docs-zh

33

Page 38: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

34 Chapter 11.

Page 39: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 12

Installation

Flask-Bootstrap can be installed using pip from PyPI. Using virtualenv is recommended – for no specific reason otherthan it being good practice. Installing is simple:

pip install flask-bootstrap

For development, clone the official github repository instead and use:

python setup.py develop

35

Page 40: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

36 Chapter 12. Installation

Page 41: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 13

Getting started

To get started, go ahead by reading Basic usage. A list of FAQ is also available.

The latest major version of Bootstrap as of this writing is Bootstrap 3. A branch of Flask-Bootstrap supporting version2 is still supported, see the page on Using Bootstrap 2 for details.

37

Page 42: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

38 Chapter 13. Getting started

Page 43: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

CHAPTER 14

A note on versioning

Flask-Bootstrap tries to keep some track of Bootstrap releases. Versioning is usually in the form of Bootstrapversion.‘‘Flask-Bootstrap iteration‘‘. For example, a version of 2.0.3.2 bundles Bootstrap version 2.0.3 andis the second release of Flask-Bootstrap containing that version.

If you need to rely on your templates not changing, simply pin the version in your setup.py.

39

Page 44: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Flask-Bootstrap, Release 3.3.7.1

40 Chapter 14. A note on versioning

Page 45: Flask-Bootstrap - Read the Docs · dependency of Flask-Bootstrap, however, and must be installed explicitly. The API ofFlask-WTFhas changed quite a bit over the last few versions,

Index

Fflashed_messages() (built-in function), 10form_button() (built-in function), 11form_errors() (built-in function), 14form_field() (built-in function), 14

Iicon() (built-in function), 11

Qquick_form() (built-in function), 13

Rrender_pagination() (built-in function), 15

41