Question

I'm making a website using twisted.web.template, where multiple pages have sub-windows with identical html code. So I want to use templates, and just dump a complete html string into place holders, wherever there is identical code. But it the twisted templating system quotes these strings (partly for security reasons it seems), so the browser can't interpret it as html. Is there any way of getting around this? It seems like a pretty normal use scenario, and is one of the basic uses of php with apache in my experience...

Some sample code. My template looks like this

<html xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">
    <body>
        <div t:render="content" />
    </body>
</html>

and my rendering class in python

class ExampleElement(Element):
    loader = XMLFile(FilePath('template.xml'))

    @renderer
    def content(self, request, tag):
        return tag('<b>This content should be in bold, but is quoted</b>')

I know for the last line I could write (with appropriate import)

return tag(tags.b('Bold content'))

but the html strings I actually want to put in are a lot bigger, and it's inconvenient having to write it like this, rather than just a single raw html string

Was it helpful?

Solution

Use a loader:

class ExampleElement(Element):
    loader = XMLFile(FilePath('template.xml'))

    extraContent = XMLFile(FilePath('extra-content.xml'))

    @renderer
    def content(self, request, tag):
        return self.extraContent.load()

Or if you really need the extra stuff to be in a string in your source file instead of in a template file:

class ExampleElement(Element):
    loader = XMLFile(FilePath('template.xml'))

    extraContent = XMLString("<b>This content will be in bold</b>")

    @renderer
    def content(self, request, tag):
        return self.extraContent.load()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top