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 中,声明了包含命名空间,并添加了 header.html 和 footer.html 的内容。以下是 templates\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>

这是 templates\heading.html 代码 −

<html>
   <head>
      <title>TurboGears Templating Example</title>
   </head>
	
   <body>
      <h1>This is page Header</h1>
   </body>
</html>

以下是templates\footer.html

<html>
   <head>
      <title>TurboGears Templating Example</title>
   </head>
	
   <body>
      <h3>This is page footer</h3>
   </body>
</html>

使用 gearbox 开始开发,并在浏览器中输入 http://localhost: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。在浏览器中输入http://localhost:8082/refinclude可获得以下输出

Footer Template