LoginSignup
3
7

More than 5 years have passed since last update.

FlaskでPCとモバイルでテンプレートディレクトリを自動で切り替えるやつ

Posted at

要件

UserAgentでPCかスマホかとか判断して、テンプレートのルートディレクトリが勝手に切り替わってほしい。

例えば、こんな感じでテンプレート用意しといて、

template/ja/pc/index.html
template/ja/sp/index.html
template/ja/fp/index.html

viewでは特にデバイス意識せずにこうしたい。pcを見るかspを見るかとかは自動でやってほしい。

return render_template('index.html', form=form)

みんなどうやってるの?

Flaskのスニペットとか探したけど、一般的な解法が見つからなかった。あったら教えてください。

Flask-Mobility というExtensionがあったけど、これはデコレータをいちいちつけなければならなくてちょっとつらい。それがPythonの流儀と言われたら、まあ、そうなのかな、と思うけど……。
あとは、PC、スマホ、ガラケーとか3つ以上分けるのとかできなさそう。
http://flask-mobility.readthedocs.org/en/latest/

作ってみた

こういうのあったらいいなってのをFlask Extensionにしてみた。
っていうか作ったの1年前だけど。

Python2系と3系どっちでもいけます。

インストールはpipで入ります。

pip install Flask-Devices

こんな感じで、任意のデバイスグループ名, UserAgentの正規表現, 対応するテンプレートディレクトリ を定義できます。

devices = Devices(app)
devices.add_pattern('mobile', 'iPhone|iPod|Android.*Mobile|Windows.*Phone|dream|blackberry|CUPCAKE|webOS|incognito|webmate', 'templates/sp')
devices.add_pattern('tablet', 'iPad|Android', 'templates/pc')
devices.add_pattern('hoge', 'hoge', 'templates/hoge')
devices.add_pattern('pc', '.*', 'templates/pc')

これを一度定義するだけで、あとは勝手にやってくれます。
どのデバイスにマッチするかは、上から順に評価します。

あとは、Viewやテンプレート上で、デバイス名を取れるのでなんか処理変えるときにも使えるよ。

@app.route("/", methods=['GET', 'POST'])
def index():
    print(request.DEVICE) # mobile, tablet, hoge, pc
    if request.DEVICE == 'pc':
        # pc
    elif request.DEVICE == 'tablet':
        # tablet
{% if request.DEVICE == 'mobile' %}<strong>今モバイルだよ。<a href="">PC版を見たいのん?</a></strong>{% endif %}

まあまあ個人的には便利に使っています。

注意点としては、uWSGI Emperorとかから使うときはテンプレートディレクトリは絶対パスで指定しないとダメかも。

おしまい。

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7