|
|||||||
1. Introduction
2. Installing Karrigell 3. The Web server 4. Configuration options 5. Working with Apache, LightTPD or Xitami 6. Programming 7. Debugging 8. Python scripts 9. CGI scripts 10. Karrigell Services 11. Python Inside HTML 12. HTML Inside Python 13. HTMLTags - generate HTML in Python 14. Including documents 15. Sessions 16. Authentication 17. Translation and Unicode |
13. HTMLTags - generate HTML in PythonThe HTMLTags module defines a class for all the valid HTML tags, written in uppercase letters. To create a piece of HTML, the general syntax is :
t = TAG(innerHTML, key1=val1,key2=val2,...)so that print t results in :
<TAG key1="val1" key2="val2" ...>innerHTML</TAG>For instance : print A('bar', href="foo") ==> <A href="foo">bar</A> To generate HTML attributes without value, give them the value
print OPTION('foo',SELECTED=True,value=5) ==> <OPTION value="5" SELECTED>For non-closing tags such as <IMG> or <BR>, the print
statement does not generate the closing tag
The innerHTML argument can be an instance of an HTML class, so that you can nest tags, like this :
print B(I('foo')) ==> <B><I>foo</I></B> Instances of the HTML classes support the addition :
print B('bar')+INPUT(name="bar") ==> <B>bar</B><INPUT name="bar"> and also repetition :
print TH(' ')*3 ==> <TD> </TD><TD> </TD><TD> </TD> If you have a list of instances, you can't concatenate the items with
Sum([ TR(TD(i)+TD(i*i)) for i in range(100) ])generates the rows of a table showing the squares of integers from 0 to 99 The innerHTML argument can be a string, but you can't concatenate a string and an instance of an HTML class, like in :
H1('To be or ' + B('not to be'))For this, use a class called TEXT , which will not generate any tag :
H1(TEXT('To be or ') + B('not to be'))A simple document can be produced by :
print HTML( HEAD(TITLE('Test document')) + BODY(H1('This is a test document')+ TEXT('First line')+BR()+ TEXT('Second line')))This will produce :
<HTML> <HEAD> <TITLE>Test document</TITLE> </HEAD> <BODY> <H1>This is a test document</H1> First line <BR> Second line </BODY> </HTML>If the document is more complex it is more readable to create the elements first, then to print the whole result in one instruction. For example :
stylesheet = LINK(rel="Stylesheet",href="doc.css") header = TITLE('Record collection')+stylesheet title = H1('My record collection') rows = Sum ([TR(TD(rec.title,Class="title")+TD(rec.artist,Class="Artist")) for rec in records]) table = TABLE(TR(TH('Title')+TH('Artist')) + rows) print HTML(HEAD(header) + BODY(title + table)) |