2012-07-23 96 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專家來理解爲什麼會這樣。