Python Pyramid & Chameleon templating language escapes html

☆樱花仙子☆ 提交于 2019-12-01 08:03:37

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>'))

Chameleon also allows ${structure: markup}.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!