簡體   English   中英

瓶子模板

[英]bottle templating

我最近遇到了瓶裝問題,這幾乎是我第一次使用模板引擎。(之前我只是簡單地制作我需要的傳統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>

我想我的主要問題是如何確保登錄框運行而不必在每個頁面插入變量

要使變量在所有模板中可用,請在路徑之前輸入類似的內容:

from bottle import BaseTemplate

BaseTemplate.defaults['symbol_name'] = value

我用它來為我的模板添加輔助函數。

更正確的解決方案可能涉及編寫插件,這不是非常困難,並且在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並將它放在一起的東西粘貼到“側邊欄”和“內容”部分到適當的位置。

還有另一種機制可以從多個模板組成頁面:包括文件。 這與上面的示例類似,例外,您的登錄頁面看起來像這樣:

<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”的模板。 在某些模板引擎中可以對其進行設置,以便每個模板都可以添加到一個部分,以便內容可以是整個模板系列的組合。

當然,也可以使用這些技術的混合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM