Turbogears-includes

提供:Dev Guides
移動先:案内検索

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 = "somepagel"/>

次の例では、root.pyにinclude()コントローラーが含まれており、includelを公開しています。

from hello.lib.base import BaseController
from tg import expose, request

class RootController(BaseController):
   @expose('hello.templates.include')
   def include(self):
      return {}

見出しとフッターHTML

includelでは、include名前空間が宣言され、headinglおよびfooterlの内容が追加されます。 これがtemplates \ includelの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 = "headingl"/>
      <h2>main content </h2>
      <xi:include href = "footerl"/>
   </body>

</html>

これがtemplates \ headinglコードです-

<html>
   <head>
      <title>TurboGears Templating Example</title>
   </head>

   <body>
      <h1>This is page Header</h1>
   </body>
</html>

以下はtemplates \ footerlです

<html>
   <head>
      <title>TurboGears Templating Example</title>
   </head>

   <body>
      <h3>This is page footer</h3>
   </body>
</html>

ギアボックスを使用して開発を開始し、ブラウザーに http://localhost:8080/include と入力します。 レンダリングされた出力は以下のようになります-

テンプレートの例

このようにして、ビューのモジュール構造を実現できます。 xi:includeディレクティブに記載されているリソースが利用できない場合、エラーが発生します。 このような場合、xi:fallbackを使用して代替リソースをロードできます。

<xi:include href = “mainl”>
   <xi:fallback href = ”defaultl”/>
</xi.include>

コンテンツを含めることは、式を含むことができるhref属性として動的にすることができます。

root.pyに次のコントローラーを追加します。

@expose('hello.templates.ref-include')
   def refinclude(self):
      return {'pages':['heading','main','footer']}

次のコードをref-includelとしてテンプレートフォルダーに保存します。

<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}l" py:for = "name in pages"/>
   </body>

</html>

サーバーを起動する前に、テンプレートフォルダに見出し、メイン、フッターがあることを確認してください。 ブラウザに http://localhost:8082/refinclude と入力して、次の出力を取得します

フッターテンプレート