如何将自己的字典传递给subtemp

2024-04-25 20:57:26 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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)

枚举每个键(如上面的示例中所示)当然不是很有伸缩性,也不是很灵活。你知道吗

那么:有没有一种方法可以传递整个环境呢?你知道吗

像这样的

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

Tags: name模板bottle字典fooincludemaintemplate
1条回答
网友
1楼 · 发布于 2024-04-25 20:57:26

只是一个想法,从我头上。(即未经测试)

@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也可以正常工作。你知道吗

相关问题 更多 >