【问题标题】:python bottle framework - How to pass dictionary to nested template?python bottle framework - 如何将字典传递给嵌套模板?
【发布时间】:2012-07-21 18:46:39
【问题描述】:

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

我的字典:

{
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>

documentation page 声明:

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

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

问候 遗传算法

【问题讨论】:

    标签: python templates bottle


    【解决方案1】:

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

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

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

    % from mybottleapp import app
    

    我不是 Python 专家,无法理解为什么会这样。

    【讨论】:

      【解决方案2】:

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

      views/index.tpl

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

      我的字典文件:

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

      这似乎对我有用。

      【讨论】:

        【解决方案3】:

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

        %include subpage1 mydict=mydict ...
        

        【讨论】:

        • 很遗憾,我不会定义该词典。它将由客户提供(基本上是各种单词的语言翻译)。所以我只想将该文件读入 mydict 并将其传递给子页面。
        • include 中的表达式 a=b 表示变量 b 将在子页面中被称为 a。 (通过引用调用)。
        • 你可以在子页面中使用相同的名称,让事情更清晰。
        • 感谢您的帮助 .. 试过了 ... 但它给出了 NameError: 'mydict' name not defined。但是,我找到了另一种方法来做到这一点。所以我会在下面回答我自己的问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-02
        • 2021-10-22
        • 1970-01-01
        • 2016-11-25
        • 1970-01-01
        相关资源
        最近更新 更多