Haml for Django developers

By : Shabda Raaj

Haml is taking the Ruby(and Rails) world by storm. Its not used as heavily by Python(and Django) developers as the Python solutions aren't as mature. I finally gave Haml a try and was pleasantly surprised how easy it was.

The most mature Python implementation of Haml is hamlpy, which converts the hamlpy code to Django templates. Others are shpaml and GHRML

Lets look at some templates from Django tutorial

{% if latest_poll_list %}
    {% for poll in latest_poll_list %}
        <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
    {% endfor %}
{% endif %}

Here is this template converted to Haml

-if latest_poll_list
  -for poll in latest_poll_list 
        %a{'href':'/polls/{{ poll.id }}'}= poll.question

You can see that this lost a lot of noise from the Django template. Being a Django programmer, significant whitespace is very pleasing.

Here is another one from the same tutorial.

<h1>{{ poll.question }}</h1>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice }}</li>
{% endfor %}

And converted to hamlpy

    = poll.question
    -for choice in poll.choice_set.all
            = choice.choice

Again, I lose a lot of noise from the templates, and the signifiant whitespace improve the chance that the out put would be valid html.

Here are a few more templates.

In particular see this which is haml for this Pinax file


  1. Haml
  2. Hamlpy

Related Posts

Can we help you build amazing apps? Contact us today.

Topics : django
© Agiliq, 2009-2012