How to use template inheritance with Chameleon?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-29 05:21:05

问题


I am using latest Pyramid to build a web app. Somehow we have started using Chameleon as the template engine. I have used Mako before and it was extremely simple to create a base template. Is this possible with chameleon as well?

I have tried to look through the docs but I can not seem to find an easy solution.


回答1:


With Chameleon >= 2.7.0 you can use the "load" TALES expression. Example:

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:


Another option, which was used prior Chameleon got an ability to load templates from the filesystem, is to pass the "base" template as a parameter.

To simplify things, I often wrap such stuff into a "theme" object:

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)

which can then be used like this:

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

Which then can be used in the template:

<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>



回答3:


Make a template here:

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

with contents:

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

Use the template here:

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

by inserting the contents:

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


来源:https://stackoverflow.com/questions/11013452/how-to-use-template-inheritance-with-chameleon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!