有没有办法将当前作用域内的所有变量作为上下文传递给Mako?
我有一个这样的函数:
def index(self):
title = "test"
return render("index.html", title=title)
在这里,render
是一个函数,它会自动把给定的模板文件和其他传入的变量一起渲染出来。在这个例子中,我把 title
作为一个变量传入上下文中。这样做对我来说有点多余。有没有什么办法可以自动获取在 index
方法中定义的所有变量,并把它们全部作为上下文的一部分传给 Mako 呢?
2 个回答
0
看看这个代码片段:
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
的变量。我觉得在实时情况下用函数是做不到的,但用类似乎可以。
2
使用下面的方法:
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
)都传递过去。