2012-07-23 58 views
2

我正在使用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状态:

*The %include Statement: You can include other templates using the %include sub_template [kwargs] statement. The sub_template parameter specifies the name or path of the template to be included. The rest of the line is interpreted as a comma-separated list of key=statement pairs similar to keyword arguments in function calls. They are passed to the sub-template analogous to a SimpleTemplate.render() call. The **kwargs syntax for passing a dict is allowed too*:

然而,没有例子,对如何通过字典,这个** kwargs给子模板给出。任何人都做过这个?如果我只是说%include subpage1 mydictionary,bottle抱怨mydictionary是未定义的(即使mydictionary是全局字典[在Router.py中定义])。

问候 GA

回答

1

我身边这让做在模板文件中的以下内容:

的意见/ index.tpl里

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

mydictfile:

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

这似乎为我工作。

0

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

%include subpage1 mydict=mydict ... 
+0

不幸的是,该字典不会被我定义。它将由客户给出(基本上是各种单词的语言翻译)。所以我只想将该文件读入mydict并将其传递给子页面。 – 2012-07-23 14:57:34

+0

包含中的expresion a = b表示变量b将在子页面中被调用。 (通过参考呼叫)。 – 2012-07-23 17:02:26

+0

您可以在子页面中使用相同的名称来使事情更清晰。 – 2012-07-23 17:12:27

0

上@ GA的answer的变化,我在模板访问我的主程序中定义的变量有:

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

编辑:在Python 2.6中,我不得不使用(从mybottleapp进口。 py):

% from mybottleapp import app 

我不够Python专家来理解为什么会这样。