3

I have a jinja template with the usual boilerplate links, one of them being the "sign out" link. The URL of this link has to be generated using Users.create_logout_url() before rendering a page.

I would like to avoid having to generate this URL and add it to my render_response for every single get/post handler. I've looked into alternatives but have not found a functional way to go about this.

BaseRequestHandler

This seems like the cleanest approach, but I'm unsure how to go about it. Would it be a case of

self.vars['logout_link'] = users.create_logout_url(self.request.path))

..and then, in all standard response handlers:

return render_response('template.html', **vars)

?

Decorators

This seems like another option, although seems slightly messy. I suppose it would work in the same way (assigning the logout link to a local variable in a wrapper function).

Context Processing?

I'm using tipfy/jinja, which doesn't seem to support this as far as I can tell.

Any advice which path I should investigate further?

Thanks

Cerzi
  • 768
  • 5
  • 19

2 Answers2

6

I do something similar with Jinja / GAE and I use a BaseHandler + a template that I include. BaseHandler:

class BaseHandler(webapp2.RequestHandler):
    ...
    def render_jinja(self, name, **data):
        data['logout_url']=users.create_logout_url(self.request.uri)
        template = jinja_environment.get_template('templates/'+name+'.html')
        self.response.out.write(template.render(data))

Then I can inherit the basehandler for eg form handlers:

class FileUploadFormHandler(BaseHandler):
    def get(self):
        ...
        self.render_jinja('contact_jinja', form=form, ...
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
  • 1
    This seems like the best way to add 'globals' to render_response - thanks! – Cerzi Dec 01 '11 at 12:16
  • 1
    As a bonus, this is an excellent way to keep template rendering DRY. I knew I was doing something wrong when I was copypasting several lines of code to lay out a basic site structure :) – Anna Jan 04 '13 at 22:19
4

Having not used either framework, im not sure if there is a nice way to add it to the template. There may be some form of middleware you can implement, but as I say, I don't have experience with those frameworks.

However, have you consideded having a universal logout URL, with a handler which will give a 303 to the correct URL for the user?

Amerdrix
  • 143
  • 6