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 %}
    <ul>
    {% for poll in latest_poll_list %}
        <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
    {% endfor %}
    </ul>
{% endif %}

Here is this template converted to Haml

-if latest_poll_list
 %ul 
  -for poll in latest_poll_list 
    %li
        %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>
<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice }}</li>
{% endfor %}
</ul>

And converted to hamlpy

%h1
    = poll.question
%ul
    -for choice in poll.choice_set.all
        %li
            = 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


Resource

  1. Haml
  2. Hamlpy


Related Posts


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

Topics : django

Comments

zw0rk

What about template tags and filters?

commmenttor
Alex

Your last example can be made a lot more compact!

No idea if formatting will hold:

%h1= poll.question
%ul
-for choice in poll.choice_set.all
%li= choice.choice

commmenttor
Have Always Dreamt Of Designer Discount Sunglasses

Haml for Django developers - Agiliq Blog | Django web app development

commmenttor
Post a comment Name :

Email :

Your site url:

Comment :

© Agiliq, 2009-2012