Skip to content. | Skip to navigation

Personal tools

>>> ''.join(word[:3].lower() for word in 'David Isaac Glick'.split())



You are here: Home / Blog / Simplify your TAL with these 2 weird tricks

Simplify your TAL with these 2 weird tricks

by David Glick posted Nov 05, 2014 04:29 PM
Chameleon makes templating in Plone better.

I wanted to call attention to something Eric mentioned in his Plone Conference 2014 keynote.

If you're using the Chameleon template engine, you can interpolate variables like this:

<a href="${href}">${text}</a>

instead of the older, more cumbersome TAL syntax:

<a tal:attributes="href href" tal:content="text" />

I just discovered this myself a couple months ago. Hurray for more readable templates! (And thanks to Malthe Borch.) Chameleon is included by default in Plone 5, and can be installed as an add-on in Plone 4. (So feel free to use this in your own code, but don't use it yet in add-ons that are meant to be compatible with Plone 4).

While we're on the topic of Chameleon, let me share another trick I found recently. Sometimes I've got a template that renders a string, for example the status message for a form, and I want to add a link or some other HTML. But since there's an existing template which inserts the string without specifying the 'structure' flag, the string gets escaped and I can't inject HTML. Well, Chameleon is smart enough to check whether the variable being inserted has an __html__ method, and if so it will call it and insert the result without escaping. So we can define a class like this:

class Markup(object):
    def __init__(self, s):
        self.s = s

    def __html__(self):
        return s

and then we can just use an instance of that class where we used to use a plain string. Actually Chameleon provides a Markup class that is basically the same thing, so we can do this:

from chameleon.utils import Markup
form.status = Markup('<blink>Tada!</blink>')

Of course, remember that you are now responsible for escaping unsanitized user input yourself.