bottle.py: use get_url from any template file

A quick tip for setting default/global template variables in bottle.py: in my previous bottle.py post, I mentioned get_url, a very useful function for generating urls in a url-agnostic app. (That means you can mount your app at any url prefix, e.g. http://mywebsite.com/blog/.) Here's a way to call get_url from within your SimpleTemplate templates. When using SimpleTemplate, bottle.py offers a way (undocumented) of setting default (global) variables in template files through the BaseTemplate.defaults class variable:

BaseTemplate.defaults['symbol_name'] = value

To use get_url from any template, you can put get_url in the default global variables:

app = bottle.default_app()
BaseTemplate.defaults['get_url'] = app.get_url  # reference to function, not function call!

Now you can simply call get_url from your templates:

<a href="{{ get_url('namedroute') }}">my link</a>

Comments

comments powered by Disqus