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。渲染的輸出將如下所示:

Template Examples

這樣就可以實現檢視的模組化構建。如果 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以獲取以下輸出

Footer Template
廣告