We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

Including Element Trees in Django Templates

Jason Huggins: To me, Django feels like just another Python library… and I can plug in additional libraries (like ElementTree for XML or the python ldap library) with no pain or bondage required. The things I’ve seen of Zope 3 do say ‘its more pythonic’, but I don’t buy it when the next step says ‘now go edit this XML file’… and “now let’s write a Python interface class”. Yuck. Just let me import my little Python library and be done with it.

Here’s an ultrasimple elementtree serialization filter for Django::

# File: templatetags/elementtree_extras.py

    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)


(See Writing custom template filters for instructions on how to install this.)

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