python bottle framework - 如何将字典传递给嵌套模板?

时间:2012-07-23 14:03:36

标签: python templates bottle

我正在使用python的瓶子框架来开发一个简单的网页。我无法理解如何将字典传递给子模板。示例代码:

mydictionary:

{
message: "Hello World",
...other template vars ... 
}

Router.py

@route('/index.html')
@view('index.tpl')
def index():
    return mydictionary

视图/ index.tpl里

<body>
%include subpage1 ......  <-- need to pass mydictionary here
...other stuff ...
</body>

视图/ subpage1.tpl

<div>This is a test: {{message}}</div>

documentation page州:

  

*%include语句:您可以使用%include sub_template [kwargs]语句包含其他模板。 sub_template参数   指定要包含的模板的名称或路径。其余的   该行被解释为逗号分隔的key = statement列表   与函数调用中的关键字参数类似的对。他们通过了   到类似于SimpleTemplate.render()调用的子模板。该   **允许传递dict的kwargs语法*:

但是,没有给出关于如何将这个** kwargs传递给子模板的字典的例子。有人这样做过吗?如果我只说%include subpage1 mydictionary,瓶子抱怨mydictionary是未定义的(即使mydictionary是一个全局字典[在Router.py中定义])。

问候 GA

3 个答案:

答案 0 :(得分:1)

我通过在模板文件中执行以下操作来解决这个问题:

视图/ index.tpl里

<body>
%from mydictfile import * <-- importing mydict here
%include subpage1 mydict  
...other stuff ...
</body>

mydictfile:

mydict = {
message: "Hello World",
...other template vars ... 
}

这似乎对我有用。

答案 1 :(得分:0)

您需要关键字参数。尝试:

%include subpage1 mydict=mydict ...

答案 2 :(得分:0)

作为@ G.A. answer的变体,我在模板中访问了我的主程序中定义的变量:

% from __main__ import app
blah blah {{app.config.my_config}} blah

编辑:在Python 2.6下我必须使用(从mybottleapp.py导入):

% from mybottleapp import app

我不熟悉Python专家,理解为什么会这样。