Question

I can't make sense of chameleon's tags. I'm a django user, but decided to introduce my CompSci course mates and myself to Pyramid, since I though more lightweight = easier to learn.

At the moment the ${} tag is escaping any html tags I'm trying to output through it. In django there was some way to specify that a variable is "safe" and doesn't need to be escaped.

How can I do the same thing in Pyramid / Chameleon?

Was it helpful?

Solution

Chameleon is based on the Zope Page Templates library, so if you find the Chameleon documentation lacking, you might wish to check out the zpt docs.

In any case, there are two main ways to do this. If you are rendering using a tal:replace or tal:content tag attribute, you can use a "structure". This is done by putting structure at the beginning of the string, followed by a space, and finally the name of the template variable you wish to render. An example is shown below:

s = '''
<html>
    <head>
    </head>
    <body>
        <div tal:content="structure t">
        </div>
    </body>
</html>
'''

from chameleon import PageTemplate

pt = PageTemplate(s)

print pt(t='<p>Hi!</p>')

If you don't want to use the tal:replace or tal:content functions, you need to wrap your string in an object that the Chameleon renderer will not try to escape (meaning it has an __html__ method that returns what the string should be). Typically, this means creating a 'Literal' class as shown below:

a = '''
<html>
    <head>
    </head>
    <body>
        <div>
            ${t}
        </div>
    </body>
</html>
'''

from chameleon import PageTemplate

pt = PageTemplate(a)

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

    def __html__(self):
        return self.s

print pt(t=Literal('<p>Hi!</p>'))

OTHER TIPS

Chameleon also allows ${structure: markup}.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top