Templates
The Jinja2 Template Engine
templates/index.html: Jinja2 template
<h1>Hello World!</h1>
templates/user.html: Jinja2 template
<h1>Hello, {{ name }}!</h1>
Rendering Templates
from flask import Flask, render_template
# ...
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
Variables
Jinja2 recognizes variables of any type, even complex types such as lists, dictionaries and objects. The following are some more examples of variables used in templates:
<p>A value from a dictionary: {{ mydict['key'] }}.</p>
<p>A value from a list: {{ mylist[3] }}.</p>
<p>A value from a list, with a variable index: {{ mylist[myintvar] }}.</p>
<p>A value from an object's method: {{ myobj.somemethod() }}.</p>
Filter name Description | Description |
---|---|
safe | Renders the value without applying escaping |
capitalize | Converts the first character of the value to uppercase and the rest to lowercase |
lower | Converts the value to lowercase characters |
upper | Converts the value to uppercase characters |
title | Capitalizes each word in the value |
trim | Removes leading and trailing whitespace from the value |
striptags | Removes any HTML tags from the value before rendering |
Such as:
Hello, {{ name|capitalize }}
Control Structures
{% if user %}
Hello, {{ user }}!
{% else %}
Hello, Stranger!
{% endif %}
<ul>
{% for comment in comments %}
<li>{{ comment }}</li>
{% endfor %}
</ul>
{% macro render_comment(comment) %}
<li>{{ comment }}</li>
{% endmacro %}
<ul>
{% for comment in comments %}
{{ render_comment(comment) }}
{% endfor %}
</ul>
{% import 'macros.html' as macros %}
<ul>
{% for comment in comments %}
{{ macros.render_comment(comment) }}
{% endfor %}
</ul>
Twitter Bootstrap Integration with Flask-Bootstrap
(venv) $ pip install flask-bootstrap
from flask.ext.bootstrap import Bootstrap
# ...
bootstrap = Bootstrap(app)
templates/base.html
<div>
{% extends "bootstrap/base.html" %}
</div>
<div>
{% block title %}Flasky{%endblock%}
</div>
<div>
{%block navbar%}
</div>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Flasky</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="/">Home</a></li>
<li><a href="#">Abourt</a></li>
<li><a href="#">Contact</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="flase">
Dropdown
<span class="caret"><span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One mor separated link</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="#">Default
<span class="sr-only">(current)</span></a>
</li>
<li><a href="#">Static top</a></li>
<li><a href="#">Fixed top</a></li>
</ul>
</div>
</div>
</nav>
</div>
<div>
{%endblock%}
</div>
<div>
{%block content%}
</div>
<div class="container">
{% block page_content %} {% endblock %}
</div>
<div>
{%endblock%}
</div>
templates/index.html
<div>
{% extends "base.html" %}
</div>
<div>
{% block title %}Flasky{%endblock%}
</div>
{% block page_content %}
<div class="page-header">
<h1>Hello world!!!</h1>
</div>
templates/user.html
<div>
{% extends "base.html" %}
</div>
<div>
{% block title %}Flasky{%endblock%}
</div>
{% block page_content %}
<div class="page-header">
<h1>Hello , {{ name }} !</h1>
</div>
{% endblock %}
Flask-Bootstrap’s base template blocks
Block | name Description |
---|---|
doc | The entire HTML document |
html_attribs | Attributes inside the html tag |
html | The contents of the html tag |
head | The contents of the head tag |
title | The contents of the title tag |
metas | The list of meta tags |
styles | Cascading stylesheet definitions |
body_attribs | Attributes inside the body tag |
body | The contents of the body tag |
navbar | User-defined navigation bar |
content | User-defined page content |
scripts | JavaScript declarations at the bottom of the document |
hello.py: Custom error pages
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
templates/base.html: favicon definition
{% block head %}
{{ super() }}
<link rel="shortcut icon" href="{{ url_for('static', filename = 'favicon.ico') }}"
type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename = 'favicon.ico') }}"
type="image/x-icon">
{% endblock %}
Localization of Dates and Times with Flask-Moment
(venv) $ pip install flask-moment
hello.py: Initialize Flask-Momentfrom flask.ext.moment import Moment moment = Moment(app)
hello.py: Add a datetime variable
from datetime import datetime
@app.route('/')
def index():
return render_template('index.html',
current_time=datetime.utcnow())
templates/base.html: Import moment.js library{% block scripts %} {{ super() }} {{ moment.include_moment() }} {% endblock %}
- templates/index.html: Timestamp rendering with Flask-Moment*
<p>The local date and time is {{ moment(current_time).format('LLL') }}.</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}</p>