Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to organize code for a Flask application with multiple set of templates

I'm writing an application with Flask and I'd like to generate different code for desktop and mobile browsers. IMHO it should be a good idea to keep the application code identical and push the problem of serving different content down the stack at the template level - so it essentially becomes a matter of writing two sets of templates for the two use cases and finding a way to choose the correct one to use at every single request. I'm using the default Jinja2 template engine with Flask.

I should mention that I have no experience with Flask and I'm learning my way through it while I write code - I'm taking this as an exercise too :)

What mechanism would you use to address this problem and keep source code as clean as possible?

like image 752
Luke404 Avatar asked Nov 01 '11 00:11

Luke404


2 Answers

Replying to myself :)

I ended up using this solution:

import flask
# patch flask.render_template()
_render_template = flask.render_template
def _my_render_template(*args, **kwargs):
    if detect_mobile_browser(flask.request.user_agent.string):
        args = ('m/' + args[0],) + args[1:]
    return _render_template(*args, **kwargs)
flask.render_template = _my_render_template

so far it seems to work, and I just put "mobile templates" in an m/ subdirectory.

like image 78
Luke404 Avatar answered Oct 10 '22 17:10

Luke404


I would like to point you in a probably somewhat different direction.

A lot of designers and developers (me included) don't see the future of website design in having the templates separated but in having one template which responds to its environment dynamically. That is it reorders its elements in a way that suites best for the given display.

It is called responsive design. I know that this is probably not the solution you have been looking for but it could become a way better one.

like image 30
Octavian A. Damiean Avatar answered Oct 10 '22 18:10

Octavian A. Damiean