我有这样的方法:
def index(self):
title = "test"
return render("index.html", title=title)
Whererender
是一个函数,它会自动呈现给定的模板文件,并将其余变量作为其上下文传入。在这种情况下,我将title
作为上下文中的变量传入。这对我来说有点多余。有什么方法可以自动获取index
方法中定义的所有变量并将它们作为上下文的一部分传递给 Mako?
使用下面给出的技术:
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()
当您运行上述脚本时,它会打印
{'subject': 'A subject', 'title': 'A title'}
显示vars
字典可以用作模板上下文,就像您像这样进行调用一样:
render("index.html", title='A title', subject='A subject')
如果使用locals()
,它将传递index()
函数体中定义的局部变量以及传递给的任何参数index()
- 例如self
方法。
看看这个片段:
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)
当你运行它时,它会吐出这个:
a=b
__module__=__main__
e=f
c=d
foo=['bar', 'baz']
__doc__=None
locals()['bar']
块引用类本身bar
,并vars()
返回bar
s 变量。我不认为你可以用一个函数实时地做到这一点,但是用一个类它似乎可以工作。