Configurable head with chameleon load

464 views Asked by At

When using chameleon, I can replace element from a base template using the concept of slot. Where you define a slot and fill it using another tag. As there is no container element in head, how can one add elements to head ? :

The Layout file

<html>
<head>
  <div metal:define-slot="extra_head"></div>
</head>
<body>
  ...
</body>
</html>

The content template that need to specify extra head.

<html metal:use-macro="load: main.pt">
<div metal:fill-slot="extra_head">
  <script type="text/javascript" src="http://example/script.js"></script>
</div>
...
</html>

This gets rendered in :

<html>
<head>
  <div metal:fill-slot="extra_head">
    <script type="text/javascript" src="http://example/script.js"></script>
  </div>
</head>
<body>
  ...
</body>
</html>

But there's no container tag in head so how can one define a slot to add stuff in the head ?

2

There are 2 answers

1
Sergey On

There's an alternative to using tal:omit-tag (which I'm finding annoyingly confusing - more than once I spent many minutes trying to figure out why a certain tag does not appear in the output when it's clearly present in the template, only to find tal:omit-tag neatly tucked in the far corner): if you use xml tags with tal: and metal: namespaces they won't appear in the output:

<html>
    <head>
        <metal:my-slot define-slot="extra_head"></metal:my-slot>
    </head>
    <body>
        ...
    </body>
</html>

and in the child template:

<metal:template use-macro="load: main.pt">
    <metal:any-descriptive-name fill-slot="extra_head">
        <script type="text/javascript" src="http://example/script.js"></script>
    </metal:any-descriptive-name>
    ...
</metal:template>

Note how the template becomes much more readable and self-descriptive and does not contain weird things such as a <div> inside <head> :)

You also can omit tal: and metal: prefixes on attributes when using namespaced tags, so

<h1 tal:condition="..." tal:content="..." tal:omit-tag="">Hi there! Bogus content for added confusion!</h1>

becomes

<tal:greeting condition="..." content="..." />
0
Kristian Benoit On

To remove the tag one has to use tal:omit-tag :

In the content template, use :

<html metal:use-macro="load: main.pt">
<div metal:fill-slot="extra_head" tal:omit-tag="">
  <script type="text/javascript" src="http://example/script.js"></script>
</div>
...
</html>

The div is not part of the result. Read the doc.