Reverse Templates

I've been using Django's templating language a lot recently and it pretty much hits the right 80-20 point for me. In general, a templating language with basic conditionals and for-loops is a great way of specifying how a complex data structure is to be serialized as a string. It certainly beats writing generation code.

But that got me thinking—if a template can take the place of generation code to go from abstract data structure to surface syntax string, can it also take the place of parsing code to go from surface syntax string to abstract data structure?

Obviously some templates are irreversible but a good number of them should be usable to driving parsing.

So imagine you have a data structure which is a list of people with a first name and last name and you have a template like this (in Django's templating language):

    {% for person in person_list %}
        <person><first>{{ person.first_name }}</first><last>{{ person.last_name }}</last></person>
    {% endfor %}

Note that I've deliberately chosen element names which differ from the names used in the data structure.

It would be relatively straightforward to create a person_list data structure from an XML instance using this template in reverse.

One challenge is that there's no indication of whether the person variable is a dictionary or an instance of, say, a Person class with attributes first_name and last_name.

Has anyone done this sort of thing? I can't imagine it's anything new.

Note that, despite the example, it's not restricted to XML, so this isn't just an XML data binding. It could be used for many appropriate file formats. vCard comes to mind, for example.

The original post had 5 comments I'm in the process of migrating over.