Roland Pish Roland Pish - 1 year ago 185
Python Question

Bottle py and Jinja2 global variable

I am using framework along with Jinja2 templates in a new application.

Whenever a user logs into the application I would like to add a new global Jinja2 variable with the name of the active user, so in a partial template (the header) I can display this name.

In my python (bottle) file I've tried several things according to what I googled so far, but no success yet.

This is the last thing I tried inside a function:

import jinja2
env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'))
env.globals['myglobal'] = 'My global'
#env.globals.update({'myglobal': 'My global'})

But, when putting this into the header template: {{myglobal}} it simply doesn't show up.

Since this is my first time with bottle and jinja2 anyone knows how can achieve this?

Answer Source

In this case you need to use before_request hook, just like below:

from bottle import Jinja2Template

def before_request():
    Jinja2Template.defaults['myglobal'] = 'My global'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download