I have a method like so:
def index(self):
title = "test"
return render("index.html", title=title)
Where render is a function that automatically renders the given template file with the rest of the variables passed in as it's context. In this case, I'm passing title in as a variable in the context. This is a little redundant for me. Is there any way I can automatically pick up all variables defined in the index method and pass them all as part of the context to Mako?
Use the technique given below:
def render(template, **vars):
# In practice this would render a template
print(vars)
def index():
title = 'A title'
subject = 'A subject'
render("index.html", **locals())
if __name__ == '__main__':
index()
When you run the above script, it prints
{'subject': 'A subject', 'title': 'A title'}
showing that the vars dictionary could be used as a template context, exactly as if you had made the call like this:
render("index.html", title='A title', subject='A subject')
If you use locals(), it will pass local variables defined in the body of the index() function as well as any parameters passed to index() - such as self for a method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With