【问题标题】:Is there any way to pass all variables in the current scope to Mako as a context?有没有办法将当前范围内的所有变量作为上下文传递给 Mako?
【发布时间】:2011-08-26 04:37:37
【问题描述】:
我有这样的方法:
def index(self):
title = "test"
return render("index.html", title=title)
render 是一个函数,它会自动呈现给定的模板文件,并将其余变量作为其上下文传入。在这种情况下,我将title 作为上下文中的变量传递。这对我来说有点多余。有什么方法可以自动提取index 方法中定义的所有变量并将它们作为上下文的一部分传递给 Mako?
【问题讨论】:
标签:
python
templates
mako
【解决方案1】:
看看这个sn-p:
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() 返回 bars 变量。我不认为你可以用一个函数实时地做到这一点,但是用一个类它似乎可以工作。
【解决方案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 用于方法。