Skip to content Skip to sidebar Skip to footer

How To Avoid Duplicating Context-setting-up Procedure When Using Base Template?

When using jinja2, base 'skeleton' template are often extended by many other templates. One of my base templates require certain variables in the context, and everywhere I use this

Solution 1:

You can add context processors to your app or blueprint. These inject extra values into the Jinja context. These aren't part of any view, but will run in the request context so you have access to everything you normally would in a view.

@app.context_processor
def base_context():
    return {
        'author': 'davidism',
        'last_update': interesting_function()
        'headers': db.query(MyModel.category).distinct().all()
    }

Processors added on a blueprint are only available to templates rendered from a view on that blueprint.

Context passed to the render_template functions will override these default context values (if they have the same key).


Solution 2:

One way I can think of is to use a decorator that provides extra context variables to each view's result.


Solution 3:

You can use macros on Jinja2 or custom Filters:

Macros:

http://jinja.pocoo.org/docs/dev/templates/#macros

you can register your custom filters with decorators like this:

https://github.com/dpgaspar/Flask-AppBuilder/blob/master/flask_appbuilder/filters.py


Post a Comment for "How To Avoid Duplicating Context-setting-up Procedure When Using Base Template?"