Is there any way to pass all variables in the current scope to Mako as a context?
I have a method like so:
def in开发者_运维问答dex(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.
Look at this snippet:
def foo():
class bar:
a = 'b'
c = 'd'
e = 'f'
foo = ['bar', 'baz']
return vars(locals()['bar'])
for var, val in foo().items():
print var + '=' + str(val)
When you run it, it spits this out:
a=b
__module__=__main__
e=f
c=d
foo=['bar', 'baz']
__doc__=None
The locals()['bar']
chunk references the class bar
itself, and vars()
returns bar
s variables. I don't think you can do it with a function in realtime, but with a class it seems to work.
精彩评论