For web application, sometimes we need to create HTML element on the server side (for example, on Google App Engine Python) and serve the webpage to the client side (user browser). There are two different ways to create HTML elements in Python script on server side:
- Write HTML code directly: This means you write the HTML code directly, and serve the code directly to user client browser.
The following example will give demonstration on how to create HTML elements in both ways.
In this example, we will try to create a div element, and append an anchor element to the div element.
1. Write HTML code directly
It's very easy and requires no explaination. Just write the HTML code as you did while editing a HTML document file, put the code in the python string and serve it to user client browser:
HTMLcode = '<div><a href="www.google.com">Google Search</a></div>' # serve the HTML code to client on Google App Engine Python using webapp2 self.response.out.write(HTMLcode)
2. Use Python xml.dom.minidom library
If you have no idea of what Python minidom is, please refer to series of introduction to minidom library in this blog . The result of following code snippet is exactly the same as that of the above code snippet, i.e., HTMLcode above is the same as div.toxml() below.
import xml.dom.minidom impl = xml.dom.minidom.getDOMImplementation() dom = impl.createDocument(None, 'div', None) div = dom.documentElement a = dom.createElement('a') a.setAttribute('href', 'www.google.com') a.appendChild(dom.createTextNode('Google Search')) div.appendChild(a) # serve th DOM to client on Google App Engine Python using webapp2 self.response.out.write(div.toxml())
|||Python Library xml.dom.minidom Howto|