bottlemakobeaker

Set a global variable for all mako templates using bottle?


I'm using bottle with beaker as session middleware. I'd like to include my session object in all my mako templates without specifying it when rendering:

Instead of this:

return mako_template("myView", { 
    "session" : bottle.request.environ.get('beaker.session') 
})

just do this:

return mako_template("myView")

Is this possible? If so, how?


Solution

  • I don't know about Mako templates, but for Bottle SimpleTemplates you can use BaseTemplate.default:

    bottle.BaseTemplate.defaults['session'] = bottle.request.environ.get('beaker.session')
    

    However, since you are setting that at application instantiation time, bottle.request may not be valid. So you may need to turn it into something that does lazy evaluation when the value is requested.

    Perhaps BaseTemplate.defaults gets fed into the Mako templates, or maybe Mako provides a similar mechanism for setting the defaults?

    I hope this helps point you in the right direction.