3

I am using bottle.py 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?

Roland Pish
  • 815
  • 1
  • 9
  • 21

3 Answers3

4

I have a similar setup, and this works for me using the BaseTemplate built into bottle:

from bottle import BaseTemplate
BaseTemplate.defaults['myglobal'] = 'My global'
Dan Gayle
  • 2,277
  • 1
  • 24
  • 38
  • My answer was a solution to the actual question, using the variables the op used in their question. Please don't re-write it into something entirely different, although that answer might be correct it is not *my* answer. – Dan Gayle Aug 09 '16 at 19:04
  • Well, I don't see anywhere in the question `BaseTemplate` and the question is Jinja2 specific. I only edited your answer to try and help others. If it's your will to keep it like that, then it's fine to me. – tleb Aug 12 '16 at 12:01
2

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

from bottle import Jinja2Template

@hook('before_request')
def before_request():
    Jinja2Template.defaults['myglobal'] = 'My global'
GBlach
  • 69
  • 4
  • 2
    Not sure you want to execute that on every `request`. Solution proposed by @DanGayle looks better to me. – Doomsday Jul 27 '16 at 21:58
1
from bottle import Jinja2Template
Jinja2Template.defaults['foo'] = 'bar'

This is to add a variable to every rendered jinja2 templates. If you want to add a filter, here is what I did:

import functools
from bottle import jinja2_view

def foo():
    return 'bar'
view = functools.partial(jinja2_view, template_settings={
    'filters': {'foo': foo}})

You can set any jinja2 settings using this.

tleb
  • 4,395
  • 3
  • 25
  • 33