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!

This post has received 44 loves.


ARCHIVE OF POSTS



This is the personal blog of Kevin Marshall (a.k.a Falicon) where he often digs into side projects he's working on for digdownlabs.com and other random thoughts he's got on his mind.

Kevin has a day job as CTO of Veritonic and is spending nights & weekends hacking on Share Game Tape. You can also check out some of his open source code on GitHub or connect with him on Twitter @falicon or via email at kevin at falicon.com.

If you have comments, thoughts, or want to respond to something you see here I would encourage you to respond via a post on your own blog (and then let me know about the link via one of the routes mentioned above).