
- TurboGears 教程
- TurboGears - 首頁
- TurboGears - 概述
- TurboGears - 環境
- TurboGears - 第一個程式
- TurboGears - 依賴項
- TurboGears - 提供模板
- TurboGears - HTTP 方法
- Genshi 模板語言
- TurboGears - 包含
- TurboGears - JSON 渲染
- TurboGears - URL 層次結構
- TurboGears - Toscawidgets 表單
- TurboGears - 驗證
- TurboGears - 快閃記憶體訊息
- TurboGears - Cookie 和會話
- TurboGears - 快取
- TurboGears - Sqlalchemy
- TurboGears - 建立模型
- TurboGears - CRUD 操作
- TurboGears - 資料網格
- TurboGears - 分頁
- TurboGears - 管理員訪問
- 授權和認證
- TurboGears - 使用 MongoDB
- TurboGears - 腳手架
- TurboGears - 鉤子
- TurboGears - 編寫擴充套件
- TurboGears - 可插拔應用程式
- TurboGears - RESTful 應用程式
- TurboGears - 部署
- TurboGears 有用資源
- TurboGears - 快速指南
- TurboGears - 有用資源
- TurboGears - 討論
TurboGears - 包含
另一個 XML 文件(尤其是 HTML 文件)的內容可以透過在當前文件中使用包含標記來包含。為了啟用此類包含,必須在 HTML 文件的根元素中宣告 XInclude 名稱空間。
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:xi = "http://www.w3.org/2001/XInclude >
上述宣告指定 include 指令包含“xi”字首。要在當前文件中新增另一個 html 頁面的內容,請按如下方式使用 xi:include 指令:
<xi:include href = "somepage.html" />
在以下示例中,root.py 包含 include() 控制器,它公開 include.html。
from hello.lib.base import BaseController from tg import expose, request class RootController(BaseController): @expose('hello.templates.include') def include(self): return {}
標題和頁尾 HTML
在 include.html 中,聲明瞭 include 名稱空間,並添加了 heading.html 和 footer.html 的內容。以下是模板\include.html 的 HTML 指令碼:
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:xi = "http://www.w3.org/2001/XInclude"> <head> <title>TurboGears Templating Example</title> </head> <body> <xi:include href = "heading.html" /> <h2>main content </h2> <xi:include href = "footer.html" /> </body> </html>
以下是模板\heading.html 程式碼:
<html> <head> <title>TurboGears Templating Example</title> </head> <body> <h1>This is page Header</h1> </body> </html>
以下是模板\footer.html
<html> <head> <title>TurboGears Templating Example</title> </head> <body> <h3>This is page footer</h3> </body> </html>
使用 gearbox 啟動開發,並在瀏覽器中輸入https://:8080/include。渲染的輸出將如下所示:

這樣就可以實現檢視的模組化構建。如果 xi:include 指令中提到的資源不可用,則會引發錯誤。在這種情況下,可以透過使用 xi:fallback 載入備用資源。
<xi:include href = “main.html”> <xi:fallback href = ”default.html”/> </xi.include>
包含內容可以動態化,因為 href 屬性可以包含表示式。
在 root.py 中新增以下控制器。
@expose('hello.templates.ref-include') def refinclude(self): return {'pages':['heading','main','footer']}
將以下程式碼另存為模板資料夾中的 ref-include.html。
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:py = "http://genshi.edgewall.org/" xmlns:xi = "http://www.w3.org/2001/XInclude"> <head> <title>TurboGears Templating Example</title> </head> <body> <xi:include href = "${name}.html" py:for = "name in pages" /> </body> </html>
在啟動伺服器之前,請確保模板資料夾具有 heading.html、main.html 和 footer.html。在瀏覽器中輸入https://:8082/refinclude以獲取以下輸出

廣告