Haml is neat but fussy
I don’t usually like templating languages. Ones I’ve known before (like TT) are intended to keep both developers and designers happy, and tend to do neither: developers miss having a full language, and designers want to know why everything can’t just be html. Haml is different; it doesn’t pretend to be html (but is simple enough any html-er can read it), and it gives you access to the whole of Ruby (but encourages you to move code blocks into helpers). It’s just nice and elegant. But it’s also very fussy about layout.
On my first try with it I spent quite a while going round in circles before I realised nearly all my errors were coming from incredibly simple layout errors. Some are pretty obvious:
%h1 Hallo
works, but
%h1 Hallo
= @user.name
throws “Illegal Nesting: Nesting within a tag that already has content is illegal.”
Which is pretty annoying, as printing a variable after some constant text is one of the most common things to need to do. And Haml lets you, you just need to change the layout to:
%h1
Hello
@user.name
and all is ok. Like the error message says, if you are going to need nesting, nest before adding any content.
The layout problem which really threw me at first came with trying to nest rows in tables:
%table
- users.each do |user|
%tr
%td A
%td B .........
Haml kept throwing an Illegal Indentation error: “Only two space characters are allowed as indentation”. So I counted them, and there were exactly two space characters indenting each layer of nesting. What I didn’t notice was that my Vim setup was sneaking in tab characters at the beginning of new lines, although the ends were fine.
:set expandtab and :%retab fixed everything. Moral: read the error messages, in Haml they do really mean what they say.
Chip on 01 Feb 2008 at 1:45 am #
Thanks for your post! Although I was using TextMate instead of Vim, I was getting Haml errors such as this:
==================================
Illegal Indentation: Only two space characters are allowed as tabulation.
Extracted source (around line #):
==================================
It referenced the correct haml file, but I wasn’t sure what line needed to be fixed. As a workaround, I left-justified all lines and the error went away. This takes away from the beauty of Haml, as it makes the template more difficult to read. However, the error is solved, so I’m relieved.
Thanks again for the pointer!
Chip
Nathaniel Bibler on 13 Apr 2008 at 10:49 pm #
A better alternative to left justifying all of your code is to modify the tab setting in the bottom center of the TextMate window.
By default the setting reads, “Tab space: 2,” which has TextMate enter tab characters into your document, but only display each of them as to 2 spaces in the displayed document. If you check the “Soft spaces” option at the bottom of that list, it won’t insert those tabs and instead insert two actual space characters.
Changing that setting should fix error mentioned in the comment above.