Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有办法将当前作用域中的所有变量作为上下文传递给Mako?_Python_Templates_Mako - Fatal编程技术网

Python 有没有办法将当前作用域中的所有变量作为上下文传递给Mako?

Python 有没有办法将当前作用域中的所有变量作为上下文传递给Mako?,python,templates,mako,Python,Templates,Mako,我有这样一种方法: def index(self): title = "test" return render("index.html", title=title) 其中,render是一个自动呈现给定模板文件的函数,其中传递的其余变量作为其上下文。在本例中,我将title作为上下文中的变量传入。这对我来说有点多余。是否有任何方法可以自动提取index方法中定义的所有变量,并将它们作为上下文的一部分传递给Mako?查看此代码片段: def foo(): class bar:

我有这样一种方法:

def index(self):
    title = "test"
    return render("index.html", title=title)
其中,
render
是一个自动呈现给定模板文件的函数,其中传递的其余变量作为其上下文。在本例中,我将
title
作为上下文中的变量传入。这对我来说有点多余。是否有任何方法可以自动提取
index
方法中定义的所有变量,并将它们作为上下文的一部分传递给Mako?

查看此代码片段:

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变量。我不认为你可以用一个函数实时完成,但用一个类它似乎可以工作。

使用下面给出的技巧:

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