Including Element Trees in Django Templates

in this tutorial we will see how to use Elementtree module in Django templates.

Here’s an ultra simple elementtree serialization filter for Django::

# File: templatetags/elementtree_extras.py

try:
    import cElementTree as ET
except ImportError:
    from elementtree.ElementTree as ET

from django.core import template

register = template.Library()

##
# Serializes an element structure to XHTML (or just plain XML).

def tostring(elem):
    "Serialize element structure to XHTML."
    if not ET.iselement(elem):
        return elem
    return ET.tostring(elem)

register.filter(tostring)

With this in place, you can return element structures from your model view, and explicitly render required trees from the template:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
{% load elementtree_extras %}
<html><head>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
<title>{{ title|escape }}</title>
</head>
{{ body_elem|tostring }}
</html>

If you accidentally leave out the tostring filter, the element tree will be rendered as “<Element ‘body’ at 00A83C90>” or something similar (which means that you may have to look at the page source to see it).