pythonchameleon

Python short-hand for HTML insertion


In the documentation we find this:

${...} operator

The ${...} notation is short-hand for text insertion. The Python-expression inside the braces is evaluated and the result included in the output (all inserted text is escaped by default):

 <div id="section-${index + 1}">
    ${content}
 </div>

To escape this behavior, prefix the notation with a backslash character: \${...}.

How can I render the content value as HTML instead of text?


Solution

  • To avoid escaping, use the structure: prefix:

    <div>${structure: content}</div>
    

    You can also pass an object with a __html__ method:

    Note that if an object implements the __html__ method, the result of this method will be inserted as-is (without XML escaping).

    Update:

    As requested, here is an example of how I think the __html__ method should work. Note that I'm not a Chameleon user and that this code untested :)

    class Unescaped(object):
        def __init__(self, value):
            self.value = value
    
        def __html__(self):
            return self.value
    

    In your template:

    <div>${ Unescaped(content) }</div>