Flask-Mobility¶
Configuration¶
There are two settings that you can change in the config for your application:
- MOBILE_USER_AGENTS
A regex for detecting mobile user agents.
Defaults to:
'android|fennec|iemobile|iphone|opera (?:mini|mobi)'
- MOBILE_COOKIE
The name of the cookie to set if the user prefers the mobile site.
Defaults to:
'mobile'
Changes to the global g
Object¶
If the current request is for the mobile site, g.is_mobile ==
True
. At all other times g.is_mobile == False
.
How is the value of g.is_mobile
determined?¶
g.is_mobile
will be set to True
if one of the following
cases are satisfied:
The user agent string in the request headers matches
MOBILE_USER_AGENTS
and theMOBILE_COOKIE
is not set tooff
.MOBILE_COOKIE
is set toon
Decorators¶
mobile_template¶
This decorator is used to pass an alternate template name to a view function for mobile requests:
from flask_mobility.decorators import mobile_template
@mobile_template('dir/{mobile/}template.html')
def view(template):
...
This will pass through 'dir/mobile/template.html'
as template
where g.is_mobile
is set to True
. When g.is_mobile
is False
it will pass through 'dir/template.html'
as
template
.
mobilized¶
This decorator is used to specify an alternate mobilized view function for a view:
from flask_mobility.decorators import mobilized
def view():
...
@mobilized(view)
def view():
...
In the example above the first view
function is used for the
normal site and the second function is used to show the mobile site.
Example¶
example.py
1#!/usr/bin/env python
2from flask import Flask, render_template
3from flask_mobility import Mobility
4from flask_mobility.decorators import mobile_template
5
6
7app = Flask(__name__)
8Mobility(app)
9
10
11@app.route("/")
12@mobile_template("{mobile/}index.html")
13def index(template):
14 return render_template(template)
15
16
17if __name__ == "__main__":
18 app.run(host="0.0.0.0", debug=True)
templates/base.html
1<!doctype html>
2<html>
3<head>
4 <title>Flask-Mobility example</title>
5</head>
6<body>
7 {% block content %}
8 {% endblock %}
9</body>
10</html>
templates/index.html
1{% extends 'base.html' %}
2
3{% block content %}
4 <p>Template: <strong>index.html</strong></p>
5 <p>
6 g.is_mobile:
7 <strong>{% if g.is_mobile %}True{% else %}False{% endif %}</strong>
8 </p>
9{% endblock %}
templates/mobile/index.html
1{% extends 'base.html' %}
2
3{% block content %}
4 <p>Template: <strong>mobile/index.html</strong></p>
5 <p>
6 g.is_mobile:
7 <strong>{% if g.is_mobile %}True{% else %}False{% endif %}</strong>
8 </p>
9{% endblock %}