Home Blog CV Projects Patterns Notes Book Colophon Search

Getting Started with Python Chameleon Templates

1 Dec, 2009

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:

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.