Fork me on GitHub

A Bit of Modular Web Design in Django

I found myself creating a web page intended to display a set of data objects, each object similar in format. A pretty common need. The simple thing to do would be to simply iterate over the list of data in the django template, for example:

{% for o in some_list %}
    <div>#display data here#</div>
{% endfor %}

I want to be able to re-use and centrally control how the data is displayed, anywhere on the site. I figured out a nice way to do this using Django templates within Django templates. The code looks something like this:

def index(request):
    things = get_things()
    module_template = loader.get_template("thingModuleTemplate.html")
    things_html = ""
    for thing in things.itervalues():
        thing_context = RequestContext(request,{
            'thing':thing,
        })

    thing_html = module_template.render(thing_context)
    things_html += things_html
    c = RequestContext(request,{
        'things_html':things_html,
    })
    page_template = loader.get_template('index.html')
    return HttpResponse(page_template.render(c))

The module template looks something like this:

<div>
    <div>{{thing.name}}</div>
    <div>{{thing.interesting_data}}</div>
</div>

The code basically does what a normal Django view does, which is to render a page from a template and pass in data via a variable, but that for loop generates the web module html used to display each object using ‘thingModuleTemplate.html’ On each pass through the for loop, it renders a module and adds it to the thingsHtml variable. Displaying the data on the index.html template is as simple as (using the ‘safe’ tag so that things_html is treated as html and not automatically escaped):

Robert Arles

Comments !

social