Setting global variable in Jinja2

4,179 views
Skip to first unread message

akindo

unread,
Apr 19, 2012, 9:04:14 AM4/19/12
to pocoo-libs
Hi fellow Jinjaers,

I am setting a global Jinja2 variable in my Python 2.7/Webapp2 code
and then displaying this variable in a base HTML page on all sections
of my site. However, after about 15 min, the variable ceases to exist
or perhaps loses its assignment. Is there some kind of timeout? Or am
I doing something wrong, please see my code below.

def jinja2_factory(app):
j = jinja2.Jinja2(app)

j.environment.filters.update({
# Set filters.
# ...
})

j.environment.globals.update({
# Set global variables.
'uri_for': webapp2.uri_for
})

return j


class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(factory=jinja2_factory)

def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
context['logged_in'] = self.logged_in

self.response.write(self.jinja2.render_template(_template,
**context))


class HelloWorldHandler(BaseHandler):
def get(self):
self.jinja2.environment.globals['username'] = 'johndoe'
context = {'message': 'Hello world.'}
return self.render_response('hello.html', **context)


In the template I then display the global var by using {{ username }}.

Thanks for your help.

Bob Rupholdt

unread,
Sep 29, 2012, 9:11:55 PM9/29/12
to pocoo...@googlegroups.com
How did you end up fixing this?  I'm trying to do something very similar.

Bob
Reply all
Reply to author
Forward
0 new messages