python瓶框架-如何将字典传递给嵌套模板? [英] python bottle framework - How to pass dictionary to nested template?

查看:115
本文介绍了python瓶框架-如何将字典传递给嵌套模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

mydictionary:

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

Router.py

Router.py

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

视图/索引.tpl

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

views / subpage1.tpl

views/subpage1.tpl

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

文档页面指出:


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

*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,瓶子会抱怨mydictionary是未定义的(即使mydictionary是全局dict [在Router.py中定义])。

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]).

考虑
GA

regards GA

推荐答案

通过在模板文件中执行以下操作:

I got around this by doing the following in the template file:

views / index.tpl

views/index.tpl

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

mydictfile:

mydictfile:

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

这似乎对我有用。

这篇关于python瓶框架-如何将字典传递给嵌套模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆