Python Pyramid & Chameleon templating language escapes html

前端 未结 2 556
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 01:52

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 = easie

相关标签:
2条回答
  • 2021-01-14 02:47

    Chameleon also allows ${structure: markup}.

    0 讨论(0)
  • 2021-01-14 02:51

    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>'))
    
    0 讨论(0)
提交回复
热议问题