DEV Community

Robert Rees
Robert Rees

Posted on

Flask: template context processors

Template context processors allow values to be injected into the the template rendering context before rendering occurs.

They are essentially very simple functions that return a map whose keys will be available as "global" variables in the template rendering phase.

It allows you to avoid boilerplate code in the request handlers and makes sure that the data passed in the render_template is specific to that route and handler.

Use cases

Template context processors work best when the data you want to use is relatively static, say configuration information that is fixed at app initialisation, cached data or things that are easy to programatically generate, such as the names of the last six months.

Because the processor is called on every render call you want to make sure it is either fast and efficient or necessary.

Commonly you use it for information that is needed on every page; things that are part of your root template. Typically this means things like analytics configuration, exception reporting, navigation and footer links.

While you can use them to attach information to the user context or calculate data based on the current user I think that can be quite dangerous and its better to keep user-dependent data out of the template processors.

Installing your processors

There is a processor annotation that you can apply to a function or you can call context_processor on the app object itself which I think is clearer.

You can register multiple processors by calling the context_processor multiple times with different arguments but that's not completely obvious and it might be better to compose your processors into a single function yourself.

Further reading

Top comments (0)