[Twisted-web] HTML Rendering with Twisted.Web
Jo as Queeniebee
joasqueeniebee at gmail.com
Wed Jun 26 09:52:06 MDT 2013
Hello,
I've asked a question before about using Jinja2 with Twisted.Web, but now I
have a more general question about rendering HTML docs within a Twisted web
application.
All the examples on TwistedMatrix.com and the txTemplate adapter show that
you pass the web page by either returning it as a string from render_Get or
as a param in .render(). Is this true for all cases? This seems a bit
inefficient when you have a file larger than <html><body> Hello,
World!</body></html>.
I've written an HTML file complete with .css and .js. How to I pass that
document to my Twisted.Web resource? When I use the code below, the context
replaces all markup from my HTML file. How do I get around this? How do you
pass a larger HTML file to Twisted.Web?
# -*- coding: utf-8 -*
import os, sys
from twisted.application import internet
from twisted.web.resource import Resource
from twisted.web import server
from twisted.internet import reactor
import txtemplate
TEMPLATE_DIR =
os.path.join(os.path.dirname(os.path.abspath(__file__)),"templates")
class ThreadResource(Resource):
def __init__(self):
resource.Resource.__init__(self)
self.loader = txtemplate.Jinja2TemplateLoader(TEMPLATE_DIR)
def getChild(self, name, request):
return self
def render_GET(self, request):
template_name = "base.html"
template = self.loader.load(template_name)
context = {"greeting": "Enter"}
def cb(content):
request.write(content)
request.setResponseCode(200)
request.finish()
d = template.render(**context)
d.addCallback(cb)
return server.NOT_DONE_YET
site = server.Site(ThreadResource())
reactor.listenTCP(8888, site)
reactor.run()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://twistedmatrix.com/pipermail/twisted-web/attachments/20130626/d50e89ee/attachment.html>
More information about the Twisted-web
mailing list