ZPT Zope Page Templates  

Zope Page Templates is a Python package that implements Page Templates like in Zope, but works outside of Zope. In fact, you don't need to install any part of Zope to use them. This means that you can use the elegance and ease of page templates in your own web applications, reporting frameworks, documentation systems, etc.

Using Zope Page Templates in Your Projects

The actual syntax of the Page Templates is explained on Zope's ZPT web page. However, since the Page Templates aren't in Zope anymore you have to do a little work to give the Page Template a namespace to work with. Below are some possible ways that you can use Page Templates in your own projects.

When in Zope, Page Templates get their namespace from the Zope database. In your projects, you'll have to populate the namespace yourself. This is fairly easy to do by creating your own Page Template class and overriding one key method.

from ZopePageTemplates import PageTemplate

class PageTemplate(PageTemplate):
   def __call__(self, context={}, *args):
      if not context.has_key('args'):
         context['args'] = args
      return self.pt_render(extra_context=context)
Now that we have a way to pass in a namespace, we can create a simple Page Template and render it. To put your Page Template file into a Page Template instance, you use the write() method.
pt = PageTemplate()
pt.write("<div tal:content="here/title">Temporary title</div>")
Create the namespace for the Page Template:
class MyClass:
   def title(self): 
      return 'This is my title'
context = {'here':MyClass()}
Render the Page Template with the context we created:
print pt(context=context)
This will give you the following output:
<div>This is my title</div>

Using Macros for a Standard Look-and-Feel

Macros can be used to create a standard look-and-feel for a website. In order to use them, you have to put the Page Templates with the macros in them into your namespace. The code below shows how this can be accomplished.

# Define the look-and-feel
lookandfeel = PageTemplate()
<html metal:define-macro="pagelayout">
   <title metal:define-slot="title">Page Layout Title</title>
   <link rel="stylesheet" href="mystyles.css">
<body metal:define-slot="body">
Page Layout Macro

# Define the Page Template with the real content
mytemplate = PageTemplate()
<html metal:use-macro="here/lookandfeel/macros/pagelayout">
   <title metal:fill-slot="title">My Template Title</title>
<body metal:fill-slot="body">
Template Content

# Render the template
print mytemplate(context={'here':globals()})

The output will look like:

   <title>My Template Title</title>
   <link rel="stylesheet" href="mystyles.css">
Template Content

Please direct any comments, questions, bug reports, and donations to Kevin Smith.