【问题标题】:How to use template inheritance with Chameleon?如何在 Chameleon 中使用模板继承?
【发布时间】:2012-06-16 07:50:13
【问题描述】:

我正在使用最新的 Pyramid 构建网络应用程序。不知何故,我们开始使用 Chameleon 作为模板引擎。我以前用过 Mako,创建一个基本模板非常简单。变色龙也可以吗?

我已尝试查看文档,但似乎找不到简单的解决方案。

【问题讨论】:

    标签: python pyramid chameleon template-metal


    【解决方案1】:

    在 Chameleon >= 2.7.0 中,您可以使用“加载”TALES 表达式。示例:

    main.pt:

    <html>
    <head>
        <div metal:define-slot="head"></div>
    </head>
    <body>
        <ul id="menu">
            <li><a href="">Item 1</a></li>
            <li><a href="">Item 2</a></li>
            <li><a href="">Item 3</a></li>
        </ul>
        <div metal:define-slot="content"></div>
    </body>
    </html>
    

    my_view.pt:

    <html metal:use-macro="load: main.pt">
    
    <div metal:fill-slot="content">
        <p>Bonjour tout le monde.</p>
    </div>
    
    </html>
    

    【讨论】:

      【解决方案2】:

      在 Chameleon 能够从文件系统加载模板之前使用的另一个选项是将“基本”模板作为参数传递。

      为了简化事情,我经常将这些东西包装成一个“主题”对象:

      class Theme(object):
      
          def __init__(self, context, request):
              self.context = context
              self.request = request
      
          layout_fn = 'templates/layout.pt'
      
          @property
          def layout(self):
              macro_template = get_template(self.layout_fn)
              return macro_template
      
          @property
          def logged_in_user_id(self):
              """
              Returns the ID of the current user
              """
              return authenticated_userid(self.request)
      

      然后可以这样使用:

      def someview(context, request):
         theme = Theme(context, request)
         ...
         return { "theme": theme }
      

      然后可以在模板中使用:

      <html
          xmlns="http://www.w3.org/1999/xhtml"
          xmlns:tal="http://xml.zope.org/namespaces/tal"
          xmlns:metal="http://xml.zope.org/namespaces/metal"
          metal:use-macro="theme.layout.macros['master']">
      <body>
          <metal:header fill-slot="header">
              ...
          </metal:header>
          <metal:main fill-slot="main">
              ...
          </metal:main>
      </body>
      </html>
      

      【讨论】:

      • Chameleon 支持直接从文件系统加载模板;查看user1456346提供的答案
      【解决方案3】:

      在这里制作模板:

      <proj>/<proj>/templates/base.pt
      

      内容:

      <html>
        <body>
          <div metal:define-slot="content"></div> 
        </body>
      </html>
      

      在此处使用模板:

      <proj>/<proj>/templates/about_us.pt
      

      通过插入内容:

      <div metal:use-macro="load: base.pt">
          <div metal:fill-slot="content">
              <p>Hello World.</p>
          </div>
      </div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-07
        • 1970-01-01
        • 2015-04-18
        • 2018-05-23
        • 1970-01-01
        • 2011-11-08
        • 1970-01-01
        相关资源
        最近更新 更多