Skip to content

Instantly share code, notes, and snippets.

@nottsknight
Last active December 15, 2015 14:28
Show Gist options
  • Save nottsknight/5274436 to your computer and use it in GitHub Desktop.
Save nottsknight/5274436 to your computer and use it in GitHub Desktop.
Python module providing a series of functions to generate various forms of HTML element, for use in CGI scripts. Will be expanded as and when I need more elements!
# UTILITY FUNCTIONS
def preamble():
"""Prints the mandatory opening lines of any CGI script."""
print "Content-Type: text/html"
print
def parseCss(css):
"""Convert a CSS class or id name into a string of the form class=var or id=var, with quotes around var.
String css -> css tag to convert
- a class name should be given with a leading '.', e.g. '.myClass'
- an ID name should be given with a leading '#', e.g. '#myId'
"""
try:
if (css[0] == "."):
return ' class="{0}"'.format(css[1:])
elif (css[0] == "#"):
return ' id="{0}"'.format(css[1:])
else:
return ''
except TypeError:
return ''
# HTML HEADER ELEMENTS
def title(text):
"""Produce an HTML title.
String text -> text to place within the title
"""
print "<title>{0}</title>".format(text)
def link(href):
"""Produce an HTML link tag.
String href -> href of the stylesheet to link to
"""
print '<link rel="stylesheet" type="text/css" href="{0}">'.format(href)
# HTML BODY ELEMENTS
def h(level, text, *css):
"""Produce an HTML heading.
int level -> which level of heading to print
String text -> the text of the heading
*String css -> optional CSS class and id tags
"""
cssTags = ""
for tag in css:
cssTags += parseCss(tag)
print "<h{0}{1}>{2}</h{0}>".format(level, cssTags, text)
def p(text, *css):
"""Produce an HTML paragraph.
String text -> the text of the heading
*String css -> optional CSS class and id tags
"""
cssTags = ""
for tag in css:
cssTags += parseCss(tag)
print "<p{0}>{1}</p>".format(cssTags, text)
def tr(header, data, *css):
"""Produce an ordinary row for an HTML table.
bool header -> whether the row is a header row or not (True for header)
[String] data -> list of data to insert into the row
*String css -> optional css tags
"""
cssTags = ""
for tag in css:
cssTags += parseCss(tag)
print "<tr{0}>".format(cssTags)
for d in data:
print "<{0}{1}>{2}</{0}>".format("th" if header else "td", cssTags, d)
print "</tr>"
@nottsknight
Copy link
Author

Added functions to print title and link tags, as well as a function to iteratively print cells in a table

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment