Include variables in the template context on each page using Bottle.py

Is there the bottleneck equivalent of context processors that you get in Flask?

+6
source share
2 answers

If you use a vanilla bottle with SimpleTemplate, there is a solution I came across.

For my site, I need access to some functions in each template, app.get_url , 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 with Bottle 0.9, I have not tested the latest versions of the framework.

This behavior is undocumented, but Marcel Hellcamp explained it in this thread . Other solutions are also mentioned there:

  • Pass global variables to _vars or a similar arg pattern.
  • Create a decorator to provide default settings.

In addition, in Bottle 0.10 in the SimpleTemplate namespace new features were added related to the problem: defined , get and setdefault

+3
source

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

0
source

Source: https://habr.com/ru/post/911036/


All Articles