[Twisted-web] How to use templating with the web server

Glyph Lefkowitz glyph at twistedmatrix.com
Mon Aug 22 15:21:15 EDT 2011


On Aug 21, 2011, at 6:10 AM, Florian Lindner wrote:

> Hello,
> 
> I want to build a simple webinterface for my application and decided to use 
> twisted.web with its templating for that. This will be my first contact with 
> twisted.

In that case, welcome to Twisted!

> I had found a working example at [1].

That looks like an OK example.  I see that <http://twistedmatrix.com/users/glyph/sphinx-preview-11.0pre1/projects/web/howto/twisted-templates.html> explains this in the abstract, but it's a documentation bug that it doesn't help you tie it all together.  Please feel free to file that bug :).

> Is there a way to render a template that involves less boiler plate code? In 
> that example I had to create a template.Element class and a web.Ressource 
> class for each page I want to render. The Ressource basically looks always the 
> same for each page, just that it renders another Element class.

You can just make one Resource class that wraps an Element.  There's no need to have a different class for every one.

You might want to submit a patch to add such a class to Twisted, although I think requirements will differ between projects as far as what the features of such a class should be, so it might be best to wait on that until a few more projects can present examples of how they used it.

> Is there a way to shortcut that a bit? My standard situation will be that I 
> have a template file and an Element class containing the logic. These are 
> "mounted" somewehre in the hierarchy (like with putChild).

You can either use putChild or write resources with appropriate getChild methods; which is better depends on your application.  It might make sense to make a single Resource subclass that deals with rendering an element, and then subclass that in order to provide methods to retrieve children.

> Sorry, I'm sure I'm lacking quite a bit of insight into twisted.

It sounds like you've got the basics, actually - just remember that it's all Python code, and you can use whatever programming techniques make your life easier.  You don't need to find a magic solution to everything somewhere inside Twisted itself, just for it to work with Twisted :).

-glyph


More information about the Twisted-web mailing list