Zope Page Template macros are an alternative to viewlets for re-using HTML templates, although either macros and viewlets may be used depending on circumstance.  Those who have used other frameworks such as Django or PHP might find this method more familiar than Viewlets and Viewlet Managers for site layout.

One or more named macros may be defined in a page template file.  These macros may then be later used inside any other view, by referring to the macro from within the view page template.

For example, if we were to create a file, macros.pt as follows:

<div class="header" metal:define-macro="header">
  <h2 tal:content="context/title" />
</div>

<div class="footer" metal:define-macro="footer">
  <p>Grok 4 Noobs</p>
</div>

We could later refer to these macros in another page template like this:

<html>
<head></head>
<body>
  <div use-macro="path/to/macros/header" />
  <stuff />
  <div use-macro="path/to/macros/footer" />
</body>
</html>

Now, if the same macro is used in multiple view page templates we have only one place to change the header or footer definitions. Thats nice. 

But there's more!

A system of slots lets the template fill in bits from the calling template.  In the above example, each view has to fill in the <head /> prolog and a lot of unnecessary boilerplate code.  So let's see if we can use macros and slots to make the layout more generic.

First, let us define our macros.pt file as follows:

<html define-macro="base_page">
  <head></head>
  <body>
    <div class="header">
      <h2 tal:content="context/title" />
    </div>

    <stuff define-slot="content_area" />

    <div class="footer">
      <p>Grok 4 Noobs</p>
    </div>
  </body>
</html>

then we could simplify the definition of our view page template right down to using the macro and filling in the content_area slot:

<html metal:use-macro="path/to/macros/base_page">
  <stuff metal:fill-slot="content_area" />
</html>

which would produce HTML functionally equivalent to the first example.

This demonstrates how the system of macros and slots in Zope Page Templates can be used as the basis for site layout.  Some would find this simpler than using viewlets, but remember that unlike macros, which can fill just one slot at a time, many viewlets can "fill" the same "slot" (viewlet manager), and so can be quite a bit more flexible than macros.

Grok 4 Noobs

Macros: an alternative way to re-use HTML