Nevow Tutorial
Better HTML Generation using Stan
Be aware that this is still just introductory stuff: it's not a recommended way of doing it.
###################################################################### # Run using 'twistd -noy file.py', then point your browser to # http://localhost:8080 # A very simple Nevow site. # Don't do it this way yet. Even better ways are coming. ###################################################################### from twisted.application import service, internet from nevow import appserver from nevow import rend from nevow import loaders from nevow import tags as T from nevow import flat class MyPage ( rend.Page ): def renderHTTP ( self, ctx ): s = T.html [ T.head ( title = "Nevow Tutorial" ), T.body [ "Hi there" ] ] return flat.flatten ( s ) ###################################################################### # Nevow Boilerplate ###################################################################### application = service.Application ( "nevowdemo2" ) port = 8080 res = MyPage() site = appserver.NevowSite ( res ) webService = internet.TCPServer ( port, site ) webService.setServiceParent ( application )
This introduces Stan, a way of expressing HTML as a series of nested python expressions. It has the advantage of generating well-formed HTML, in that it guarantees that closing tags are correctly generated.
It is well worth playing around with Stan to see some of its features. In general, stan is structured as follows:
- Square brackets transform to content surrounded by a tag;
- Parentheses transform to attributes within the tags;
- Lists are flattened to be adjacent elements;
You can try out various things using nevow.flat.flatten, which is useful for experimenting with Stan as it just prints out a string so you don't need to bother with creating complete documents. For example:
from nevow import tags as T from nevow import flat from nevow import entities s1 = T.div ( _class = "foo" ) [ T.a ( href = 'bar' ) [ "Hi" ] ] print flat.flatten ( s1 ) s2 = [ T.h1 [ "This is a heading" ], T.h2 [ "This is a subheading" ], T.p [ "This is a paragraph" ] ] print flat.flatten ( s2 ) s3 = [ "Some text", entities.emsp, "Some more text" ] print flat.flatten ( s3 )
which will print:
<div class="foo"><a href="bar">Hi</a></div> <h1>This is a heading</h1><h2>This is a subheading</h2><p>This is a paragraph</p> Some text Some more text
Note the following:
- You can specify pretty much arbitrary HTML attributes inside the parentheses;
- These are attributes are actually keyword arguments, so they are unquoted;
- class and id are Python reserved words, however, so you have to use _class and _id.
- HTML entities are available in nevow.entities
If you're happy with this you can go on to DivmodNevow/TutorialThree
