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/

    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)


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"
{% load elementtree_extras %}
<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>
<title>{{ title|escape }}</title>
{{ body_elem|tostring }}

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).