瓶子模板

bottle templating

我最近接触了 bottlepy,这几乎是我第一次使用模板引擎。(之前我只是简单地用传统的 PHP 制作我需要的东西)

我的问题是,假设我有一个基本布局(一个简单的 HTML/CSS 布局),例如;侧面的登录框。如何使登录框动态保持最新,而不必在每条路线上都向其传递值?

以此为例:

from bottle import route,template

@route('/')
def main():

    return template("content.tpl") #rebase from layout.tpl

layout.tpl:

<html>
    <head>
        <title>{{title}}</title>
    </head>
    <body>
        %include
        <div id='sidebar'><!-- login box --></div>
    </body>
</html>

我想我的主要问题是如何确保登录框运行而不必在每个页面都为其插入变量

我对 bottle 不熟悉,但对于其他模板引擎,这种事情是通过继承完成的。

例如,

假设您有一个名为 content.tpl 的基本模板,它看起来类似于您的 layout.tpl:

<html>
    <head>
        <title>{{title}}</title>
    </head>
    <body>
        <div id='sidebar'>%% section "sidebar" %%</div>
        <div id='content'>%% section "content" %%</div>
    </body>
</html>

请注意,这是伪代码 - %% ... %% 标记的内容是编造的,并不对应于任何特定的模板引擎 (AFAIK)。

对于您的登录页面,您将有另一个名为 login.tpl:

的模板文件
%% extends "content.tpl" %%

%% start section "sidebar" %%
    <!-- whatever you put here will be rendered -->
    <!-- in the "sidebar" section of the parent -->
%% end section "sidebar" %%

%% start section "content" %%
    <!-- whatever you put here will be rendered -->
    <!-- in the "content" section of the parent -->

    <form> ... </form>
%% end section "content" %%

然后,在登录页面的路由中,您可以执行如下操作:

`return template("login.tpl")`

这将导致模板引擎加载 login.tpl,填写它的值,然后加载 content.tpl 并将它为 "sidebar" 和"content" 部分放入适当的位置。

还有另一种从多个模板组成页面的机制:包含一个文件。这与上面的示例类似,除了您的登录页面看起来像这样:

<html>
    <head>
        <title>{{title}}</title>
    </head>
    <body>
        <div id='sidebar'>%% include "sidebar.tpl" %%</div>
        <div id='content'>%% include "content.tpl" %%</div>
    </body>
</html>

它们之间的主要区别是:

  1. 当您继承时,您不必在每个页面上重复所有内容 - 可以从父布局继承所有页面不变的内容。

  2. 在继承时,您还可以将多个模板中的内容合并到一个模板中。例如,假设您有这样继承的模板 "main.tpl" -> "template1.tpl" -> "template2.tpl"。在某些模板引擎中可以设置为每个模板都可以添加到一个部分,这样内容就可以是整个模板系列的组合。

当然,也可以混合使用这些技术。

要使一个变量在所有模板中可用,请在您的路由之前放置如下内容:

from bottle import BaseTemplate

BaseTemplate.defaults['symbol_name'] = value

我用它来为我的模板添加辅助函数。

一个更正确的解决方案可能涉及编写一个插件,这不是很困难并​​且在 Bottle 文档中有介绍。

Source