WARNING: This page is archived and not updated. Please bear in mind any information may be incorrect and any code may not work. Use at your own risk.
James Gardner: Home > Blog > 2009 > Getting Started with Python...

Getting Started with Python Chameleon Templates

Posted:2009-12-01 12:36
Tags:Python, Pylons
Headline:Get started with Chameleon Templates using pure Python and no Zope

System Message: WARNING/2 (<string>, line 7)

Field list ends without a blank line; unexpected unindent.

dependencies. You can then use TAL and more.

Here's the code you need which is missing from the main docs:

Save this as helloworld.pt:

<div xmlns="http://www.w3.org/1999/xhtml">
  Hello World!
</div>

Then use this code, updating the path to be the directory containing the helloworld.pt template.

from chameleon.zpt.loader import TemplateLoader
pt_loader = TemplateLoader(['/home/james/Desktop/Chameleon-1.0.4/src/chameleon/tests/templates/'], auto_reload=True)
template = pt_loader.load('helloworld.pt')
result = template(a='a', b='b')

You'd replace the a='a', b='b' bit with your variables. Once you get to this stage the rest of the documentation should be very easy to follow.

You can also load from a string like this:

from chameleon.zpt.template import PageTemplate
template = PageTemplate(
    """
    <div xmlns="http://www.w3.org/1999/xhtml">
      Hello World!
    </div>
    <p tal:content="user_message">
      Designer sees this.
    </p>
    """
)
result = template(user_message='User sees this')

The result is:

<div xmlns="http://www.w3.org/1999/xhtml">
      Hello World!
    </div>
    <p>User sees this</p>

Note

The reason I'm interested in this is that I've stopped using templating languages in my code. Instead I use static HTML files as templates and I just replace certain parts with Python-generated code. (This isn't as nasty as it sounds because the static HTML files are in Dreamweaver format which supports Library Items for common elements). I therefore have no need for any inheritance features because I have a different Dreamweaver template for each page layout (made consistent with Library Items) but I would like a way for Python to be able to parse some of that HTML so that designers can work with it but so that I don't have to write all my template fragments in Python. TAL is a good fit for this as I can just use TAL-formatted HTML in the editable regions and Chameleon supports TAL. I'm not using METAL and the like though.

Further reading:

(view source)

James Gardner: Home > Blog > 2009 > Getting Started with Python...