Home > Programming & scripting, Python > querypy - Write HTML without writing HTML (by using python)

querypy - Write HTML without writing HTML (by using python)

September 20th, 2007

I’ve never liked writing HTML, so I thought that I could create a tool that does it for me… so that’s what I did.
Link here

querypy let’s you write HTML by using python with a syntax heavily inspired by jquery’s “chaining”. It uses overloaded operators to get a simple syntax that is small but still powerful. Both HTML4 and XHTML is supported, and can be chosen by using an utility function. querypy structures your code into an object oriented tree structure which makes it easy to reuse and change parts of you HTML.

It should be noted that querypy is not meant to be used as CGI to create dynamic content, but rather as a design tool for creating templates. Afterwards you should use a nice framework like perhaps django to implement the actual content.

Here is an example of usage:

from querypy import *

html, head, body = HTML(), HEAD(), BODY()
html + head
html + body

head + ( TITLE() + "A Hello World page" )

body + ( H1() + "Hello world" )

print doctype_html4_strict()
print html

Which outputs

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
  <HEAD>
    <TITLE>
      A Hello World page
    </TITLE>
  </HEAD>
  <BODY>
    <H1>
      Hello world
    </H1>
  </BODY>
</HTML>

If you prefer XHTML, simply add use_xhtml(True) before printing the root node.
Here is the same example using XHTML and more chaining.

from querypy import *

use_xhtml(True)
print doctype_xhtml_strict()
print HTML() + ( HEAD() + ( TITLE() + "A Hello World page" ) ) + \
  ( BODY() + ( H1() + "Hello world" ) )

and it’s output

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
 <head>
  <title>
   A Hello World page
  </title>
 </head>
 <body>
  <h1>
   Hello world
  </h1>
 </body>
</html>

The project can be found at http://querypy.com. Feel free to drop me feedback here or by email.

buffi Programming & scripting, Python

  1. Dave
    September 20th, 2007 at 13:02 | #1

    IMO this is a *really* stupid name for something that *doesn’t do any querying*. \*Please\* consider changing it to something that indicates \*its\* purpose.

  2. September 20th, 2007 at 13:27 | #2

    Yes, I’m not 100% pleased with the name myself, although it could work since query can mean a few things.

    http://en.wikipedia.org/wiki/Query_%28complexity%29
    “In descriptive complexity, a query is a mapping from structures of one vocabulary to structures of another vocabulary”

  3. October 10th, 2007 at 09:43 | #3

    Why would you want to write HTML in Python? :-)

  1. May 3rd, 2008 at 09:16 | #1