问题
I am using python's bottle framework to develop a simple web page. I am having trouble understanding how to pass a dictionary to a subtemplate. Example code:
mydictionary:
{
message: "Hello World",
...other template vars ...
}
Router.py
@route('/index.html')
@view('index.tpl')
def index():
return mydictionary
views/index.tpl
<body>
%include subpage1 ...... <-- need to pass mydictionary here
...other stuff ...
</body>
views/subpage1.tpl
<div>This is a test: {{message}}</div>
The documentation page states:
*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*:
However, no example is given on how to pass dictionary with this **kwargs to subtemplates. Anyone ever done this? If I just say %include subpage1 mydictionary, bottle complains mydictionary is undefined (even though mydictionary is a global dict [defined in Router.py]).
regards GA
回答1:
I got around this by doing the following in the template file:
views/index.tpl
<body>
%from mydictfile import * <-- importing mydict here
%include subpage1 mydict
...other stuff ...
</body>
mydictfile:
mydict = {
message: "Hello World",
...other template vars ...
}
This seems to be working for me.
回答2:
You need keyword arguments. try:
%include subpage1 mydict=mydict ...
回答3:
As a variation on @G.A.'s answer, I accessed a variable defined in my main program in my template with:
% from __main__ import app
blah blah {{app.config.my_config}} blah
Edit: Under Python 2.6 I had to use (to import from mybottleapp.py):
% from mybottleapp import app
I am not enough of a Python expert to understand why this is so.
来源:https://stackoverflow.com/questions/11614116/python-bottle-framework-how-to-pass-dictionary-to-nested-template