如何将自己的字典传递给子模板

how to pass own dictionary to sub-template

bottlepysimple template engine 结合使用 我想知道如何将已 传递 的整个字典传递给模板到它的子模板。

例如在我的 main.py 我有:

@bottle.route('/')
@bottle.view('main')
def index():
    """main page"""
    return {"name": "main", "foo": 12, "flag": True}

我想将所有字典中的值从我的main.tpl传递给sub.tpl

$ cat sub.tpl
<h1>Hello, {{name}}</h1>

$ cat main.tpl
% include('subtemplate', name=name, foo=foo, flag=flag)

枚举每个键(如上例所示)当然不是很可扩展也不灵活。

so:有没有办法把整个环境传过去?

类似

$ cat main.tpl
% include('subtemplate', *env)

只是一个想法,脱离了我的头脑。 (即未经测试。)

@bottle.route('/')
@bottle.view('main')
def index():
    """main page"""
    env = {"name": "main", "foo": 12, "flag": True}  # same vars as before
    env["env"] = env  # add a reference to the entire dict, for passing deeper into subtemplates
    return env

然后:

% include('subtemplate', env=env)

编辑

感谢@Kwartz 提出以下改进建议。

更简洁的方法是:

% include('subtemplate', **env)

没有尝试过,但如果 **locals() 有效(h/t @Lukas Graf 尝试并确认),那么期望 **env 也有效是合理的。