September 9th, 2011

Making a variable available to all my Python Tornado Templates

As of late I’ve been working on a handful of Python projects using the Tornado framework (which I love by the way). In that work, I’ve often run into a situation where I want to use a variable within my wrapper template and I don’t want to have to define and pass that variable within each of my python methods. So how do I do that? The answer is actually pretty simple, just extend the render method to make your variables available to every template. In the example below, I wanted to be able to show the number of credits an account has as part of my template header (probably a pretty common need). I maintain a credit count within a secure cookie, so all I really needed was a way to make sure the value of that cookie is passed and avaiable to every template. Here is the code snippet that does just that

class BaseHandler(tornado.web.RequestHandler):

    def render(self, template, **kwargs):

        # add any variables we want available to all templates

        kwargs[‘account_credits’] = self.get_secure_cookie(“credits”)

        super(BaseHandler, self).render(template, **kwargs)

…and now in any template, including my HTML wrapper, I can reasonably expect {{account_credits}} to be available (though in this example above, you should ensure that the secure cookie is set before making any other assumptions — I do this in a different part of my codebase). Anyway - that’s the simple trick I’m using right now…hopefully it helps you out too. Or if you’ve got a better solution, I would love to hear about it in the comments as well!