Include variables in template context on every page with Bottle.py

Question:

Is there a bottle.py equivalent of context processors that you get in Flask?

Asked By: Matt Swain

||

Answers:

If you’re using vanilla Bottle with SimpleTemplate, there is a solution I’ve stumbled upon.

For my site, I needed access to some functions in every template, app.get_url being obviously one of them. This worked for me:

# after app creation, but before the views
SimpleTemplate.defaults["get_url"] = app.get_url
SimpleTemplate.defaults["url"] = lambda: request.url
SimpleTemplate.defaults["fullpath"] = lambda: request.fullpath
SimpleTemplate.defaults["sorted"] = sorted

This works as of Bottle 0.9, I didn’t test on more recent versions of the framework.

This behavior is undocumented, but Marcel Hellkamp explained it in this thread. In there, other solutions are also mentioned:

  • Pass over the globals in _vars or a similar template arg.
  • Create a decorator to supply the defaults.

Also, in Bottle 0.10, new functions related to the problem were introduced in the SimpleTemplate template namespace: defined, get, and setdefault

Answered By: Helgi

Note: this same solution can be used with the other template engines. The technique is exactly the same, but you use BaseTemplate (it works for all template classes) or the class for the engine you want to use.

Answered By: nostromo

Using the previous answer from Helgi, I use this hook to make a context processor like (bottle 0.12.x) :

import bottle


@bottle.hook('before_request')
def _context_processor():
    bottle.SimpleTemplate.defaults['foo'] = 'F00'
    bottle.SimpleTemplate.defaults['bar'] = 'B@R'
Answered By: Augustin Laville
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.