0

I am using Jinja2 and Python 2.7 with App Engine.

In a request handler I would like to set a permanent variable Jinja2 variable, such that it is available for all Jinja2 templates. Specifically this is for a User object, so I always can pull out the username to display on all pages of the site when they are logged in.

I have read this question and answer: How do I access session data in Jinja2 templates (Bottle framework on app engine)?

but when I try it, the session variable does not seem to be permanent, i. e. when I browse to another template, the session variable no longer exists.

How do I set a permanent variable? And will it be independently set for each user?

Thanks for your help!

Community
  • 1
  • 1
  • Did you check wether this is a session issue or Jinja issue? An error in your session-related code seems more likely than a reputed template engine being unable to simply accept your variables. –  Apr 08 '12 at 15:20
  • I agree, I just wasn't sure if the answer I linked to really worked. Using that answer, it now works. My earlier mistake, to test whether the variable was permanently set, I would perform a request setting the variable, then comment out the line setting the variable and perform the same request to see if it was still available. This doesn't work for some reason. But if I set the variable in one request, it is available in other Jinja2 templates. –  Apr 11 '12 at 11:05

1 Answers1

0

When your Jinja environment is created on every request, your variable is not saved. Webapp2 has all the functionality you need for sessions, Jinja and saving data.

voscausa
  • 11,253
  • 2
  • 39
  • 67
  • Thanks for your answer voscausa. I had a look at the [webapp2 Sessions page](http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html) and got that working. So you are saying that I'll have to do something like `context = {'user': self.current_user} return self.render_response('user_profile.html', **context) ` each time I handle a request? Thanks. –  Apr 08 '12 at 16:40
  • I think (i have not tried this) that webapp2 with webapp2 extras jinja can save the environment object. I also think you can add globals to this environment object. The Jinja global namespace documentation states : "Variables stored in the Environment.globals dict are special as they are available for imported templates too, even if they are imported without context". – voscausa Apr 08 '12 at 20:08
  • Thanks for your help voscausa. My test to see if it would work didn't work for some reason, see above comment. –  Apr 11 '12 at 11:06