Recently when I started to redesign my blog I re-wrote a lot of the code to be more optimized. During this process of re-writing I just found a more better way to write templates. Its not very new and innovative but I found it to be a huge time saver.

During my redesign I had to re-write all my templates to change the layout and the look and feel. In this course of work I had to write chunks of code again and again, like displaying a bunch of posts. There is a lot of boiler plate code in templates which is very boring to type.

    # This is my posts_list.html (a list of my recent 10 posts).
    {% raw %}
    {% for object in object_list %}
        <h3 class="styling">{{ object.title }}</h3>
        <span class="date">{{ object.date|date:"dS F M Y" }}</span>
        <div class="entry"> {{ object.body }}</div>
    {% endfor %}
    {% endraw%}

Instead I adopted a method in my Model called ‘get_rendered_html’ which returns rendered html code. All we need to do is pass an object to the method.

    def get_rendered_html(self):
        return render_to_string('blog/entry_item.html', {'object': self })

Now place the redundant code into the entry_item.html.

    {% raw %}
    <h3 class="styling">{{ object.title }}</h3>
    <span class="date">{{ object.date|date:"dS F M Y" }}</span>
    <div class="entry"> {{ object.body }}</div>
    {% endraw %}

This way we can avoid typing redundant code in templates.

    {% raw %}
    {% for object in object_list %}
        {{ object.get_rendered_html }}
    {% endfor %}
    {% endraw %}

This approach saved me a lot of time because “search”” in my blog actually returns three types of objects entry, link and photo. In my search template I had to do ugly logic like check every object if it is entry or link or photo.

    {% raw %}
    {% ifequal object._meta.object_name "Entry" %} HTML here {{"{% endifequal %}
    {% ifequal object._meta.object_name "Link" %} HTML here {{"{% endifequal %}
    {% ifequal object._meta.object_name "Photo" %} HTML here {{"{% endifequal %}
    {% endraw %}

Huge timesaver ain’t it. Redesign always makes you re-think there by making things optimum…. )