Save Loads of Time by Writing Your HTML With Haml

by on 13th February 2012 with 17 Comments

screenshot

Odds are, by now you know all about Sass and its brethren (LESS, Stylus, etc.). Love them or hate them, these CSS preprocessors are making a big splash in the development community. In many ways they represent a faster, more efficient way to write CSS and if you get on board, you’ll no doubt appreciate the flexibility that they bring to your project.

Once you get bitten by the CSS preprocessor bug, you’ll inevitably start look at HTML and wondering why it has to be so cumbersome. Why doesn’t someone drastically simplify the way we write markup? It turns out, the same people that brought us Sass have done just that with a language called Haml. Today we’re going to take a look and see how to use Haml to completely change the way you write markup.

What Is Haml?

screenshot

At its core, Haml is a lightweight markup language. The closest equivalent that you’re probably familiar with is Gruber’s Markdown, which is functionally similar but more geared towards writers.

Like Markdown, Haml makes writing HTML much easier, and when I say “much easier” what I really mean is “you won’t believe how much time you can save by using Haml.” In my opinion, it’s even more of an obvious time saver than Sass. Many developers take one look at Sass and think, “Neat! But I don’t really see a need for it.” With Haml, almost every developer, whether they would ever consent to use it or not, should immediately see the intense timesaving benefits that it brings to the table.

Not Just For Ruby Developers

The big problem with Haml is that it can be intimidating simply because the Haml website is so geared towards Ruby developers. A casual HTML developer will stop by this site only long enough to read the statement “Haml is the next step in generating views in your Rails application.” This combined with multiple references to ERB just screams “you don’t belong here” to plain old front end developers.

This is definitely unfortunate though because as I just mentioned, everyone who writes HTML can use Haml in some respect. Sure, you won’t use all of the features, but I’m sure you don’t use all of Photoshop’s features either but you still fire it up it on a daily basis.

My point is, if you’ve never written a line of Ruby in your life and don’t plan to, don’t let that scare you off from Haml. It’s still immensely fun. Today we’ll discuss Haml purely as a way to write HTML so no matter where you are in the development spectrum you should be able to follow along.

Your First Line of Haml

Now that you have a basic idea of what Haml is on a conceptual level, it’s time to kick the tires and see how it works. Eventually, we’ll need to discuss how to compile your Haml into HTML (don’t worry, it’s effortless) but for now try to ignore that and just take in the language. When I say “compiles to” just know that we’ll cover this process soon.

The beauty of Haml is that it’s “DRY”, meaning there’s been an attempt to strip out as much of the annoying inherent HTML repetition as possible. For instance, consider the structure of tags. Here’s a standard paragraph structure:

HTML:

This is an HTML paragraph

Notice how even the simplest bit of HTML involves some repetition. The paragraph tag must be placed at the beginning of the statement, and then a corresponding closing tag must be placed at the end. What if we could skip all of this nonsense? Here’s the same statement in Haml:

Haml:

%p This is also an HTML paragraph

In Haml, we prefix HTML tags with a “%” and it takes care of the rest. But wait you implore, how does one differentiate between two elements without the closing tag? The answer is of course that Haml is whitespace dependent, meaning it uses the visual structure of your code to determine the HTML output. Here’s another example that uses multiple elements and even nests some elements inside of others (the list items are nested in the unordered list).

Haml:

%h2 This Is a Headline
%a This is a paragraph.
%ul
	%li List item one
	%li List item two
	%li List item three
%p Another paragraph can go here.

In plain old HTML, the indents in an unordered list are merely for visual guidance and don’t really have any semantic meaning. In Haml though, they tell the compiler that those list items go inside the previous tag, which in this case is a ul.

It might be difficult to wrap your brain around at first, but the code above is the code below, meaning they’re perfectly equivalent. If we type out the Haml above and feed it into a compiler, it spits out the HTML below.

HTML:

This Is a Headline

This is a paragraph.
  • List item one
  • List item two
  • List item three

Another paragraph can go here.

As you can see, the HTML version requires a lot more characters. By using Haml, we’ve saved ourselves over thirty keystrokes in this one tiny snippet. Expand this concept over an entire website and you can easily see the implications.

Classes and IDs

Without the traditional tag structure, you might be wondering how to declare extra HTML items like classes and IDs. Haml is way ahead of you and even uses a syntax that you’ll find oddly familiar.

Haml:

%ul.someClass
	%li#someID

As you can see, the “.” and “#” symbols are used to denote classes and IDs respectively. This is great because you’re already familiar with this method in CSS. That familiarity means that once you really dive in, you’ll be able to pick up Haml in no time. Here’s how this code compiles.

HTML:

Divs Are Magic

Let’s face it, even with all the fancy new HTML5 elements, we still all love our divs. Given that this particular element is so common, Haml has assigned it a particularly simple syntax. Consider how you think you might write the following HTML in Haml.

HTML:

Given what we’ve learned so far, you’ll no doubt reach the conclusion that some form of “%div” is necessary here. However, Haml allows you to skip the div syntax all together. To write the above HTML in Haml, this is all you need.

Haml:

#someDiv

That’s it! This code compiles to a complete div with an ID of “someDiv”. Even the skeptics among you have to admit that this is pretty dang concise. Once again we see the clear benefits of being able to write our markup like we write CSS.

Just to make sure you’ve really gotten the gist of how this works, here’s a much more extensive example. This time we’ll use one main div and two inner divs along with plenty of other elements.

Haml:

#container
  .box
    %h2 Some Headline
    %p Lorem ipsum doller your mom...
    %ul.mainList
      %li One
      %li Two
      %li Three
      
  .box
    %h2 Some Headline
    %p Lorem ipsum doller your mom...
    %ul.mainList
      %li One
      %li Two
      %li Three​​​

HTML:

Some Headline

Lorem ipsum doller your mom...

  • One
  • Two
  • Three

Some Headline

Lorem ipsum doller your mom...

  • One
  • Two
  • Three

This time around you can really start to feel the awesomeone power of Haml. The charm here goes beyond the fact that we’ve saved tons of characters and even a few entire lines, notice how much easier it is to read the Haml at a glance. All of the nasty clutter that comes with HTML has bee stripped away and in its place is a clear hierarchy of markup that is instantly discernible.

What About HTML5?

Just in case you’re wondering, Haml works just fine with all of the cool new tags inside of HTML5. In fact, it doesn’t really care what type of tags you try to create. If you type “%somecrazytag” the output result will be “<somecrazytag></somecrazytag>” regardless of the fact that this isn’t even valid HTML.

Here’s a quick example to illustrate that uses the new header, nav, section and footer HTML5 tags.

Haml:

.wrapper
  %header
    %nav
      %ul
        %li one
        %li two
        %li three
      
  %section
    .info
    %p Lorem ipsum doller set
    
  %section
    .info
    %p Lorem ipsum doller set
  %section
    .info
    %p Lorem ipsum doller set

  %footer
    %p Lorem ipsum doller set​​

HTML:

Lorem ipsum doller set

Lorem ipsum doller set

Lorem ipsum doller set

Lorem ipsum doller set

Mix It With HTML

One last great thing about Haml is that, just like with Sass, you can still toss in the original syntax whenever you want and everything will still compile just fine. For instance, I personally don’t like how Haml handles inserting simple text links (it’s a little quirky) so I stick to the normal HTML syntax.

Haml:

#linkExample
   %p Visit our home page.

Here I’m mixing vanilla HTML with Haml and it’s perfectly acceptable. When this compiles, the result is exactly what you’d expect it to be.

HTML:

Visit our home page.

This makes it really easy to ease into using Haml. If you come up against something that you simply can’t figure out how to do, you don’t have to spend hours of research looking for the solution, just use HTML!

Haml Sucks for Content

The more I researched Haml, the more that I realized that I’m not the only one bothered by its link syntax or other content structures. In fact, Chris Eppstein wrote a piece boldly titled Haml Sucks for Content wherein he even scored an agreement to that statement from Haml creator Nathan Weizenbaum!

Be sure to read through that post before commenting on this one as it points out many valid Haml critiques that I completely agree with. The solution offered by Eppstein is to use Haml only for “layout & design” purposes. He then proceeds to reach the same conclusion that I did: it’s ok to use HTML in your Haml. Sometimes it’s just simpler.

Eppstein also points out other possibilities such as using the Haml Markdown filter to markup your content.

Tools For Compiling Haml to HTML

This is the part where you run for the hills because I start talking about installing Ruby gems to compile your code right? Wrong. Fortunately, we don’t have to jump through any fancy hoops or even break out the command line to compile Haml. There are plenty of great tools that do it for us.

For starters, there’s the #haml.try app on the official Haml website. This allows you to type Haml into a text field and receive HTML output.

screenshot

However, if you’re looking for an online compiler you can do much better than this simple tool. I personally really like Rendera, which has a nice split view that shows your Haml input and HTML output side by side. You can even toggle between the live HTML output and the source.

screenshot

It’s also interesting to note that Tinkerbin supports Haml. It’s not the way to go if you’re looking to copy and paste the HTML output, but it’s probably the single best way around to experiment with Haml and Sass without any setup work whatsoever.

For Mac Users

If you’re looking to use Haml in your local coding environment and happen to be a Mac user, you’re in luck because there are some fantastic tools to help you out. The first thing you’ll want to download the free public beta of Chocolat, an awesome text editor that supports modest syntax highlighting for a million different languages, including Haml. There’s also been at least one attempt to create a Haml Espresso Sugar.

screenshot

Unfortunately, the only real benefit of using Chocolat is that you won’t have to type in plain text, it won’t actually compile your code for you. For that, you’ll need to look to another free public beta: Codekit.

screenshot

Codekit works with Haml, Sass, Less, Stylus and CoffeeScript. Basically, it keeps an eye on your project folder so that very time you save or update one of these types of files (in our case a .haml file), it automatically processes and outputs the standard equivalent file. Also be sure to check out Live Reload, which functions the same way but lives in your menu bar.

Conclusion

If you’ve jumped on the Sass, LESS or Stylus bandwagon and have been looking for a similar solution for HTML, Haml is your answer. It allows you to write beautifully simple code that both saves you time and can actually be easier to read once you get used to it.

The unfortunate thing about Haml is that it’s a little scary for non-Ruby-developers simply because the documentation is so geared towards Ruby. I promise though, even if you don’t know a thing about Ruby, Haml is still quite fun to dig into and experiment with for simple HTML output.

Now that we’ve covered the basics, get out there and try Haml for yourself. Be sure to check out the Haml website for more information and bookmark this Haml Cheatsheet to jump off to a quick start.

Comments & Discussion

17 Comments

  • http://www.kocoon-bien-etre.fr Christian

    Hi !

    HAML sounds really interesting.
    Is there any plugin for Eclipse/Aptana IDE ?

    thanks

  • http://roytomeij.com/ Roy Tomeij

    Those who started using Sass “back in the day” should know Haml: until not so long ago Sass was a part of Haml; you needed to install Haml to use Sass. Some time ago they were (finally) split into different projects.

  • http://shinytoyrobots.com Robin Cannon

    I really like the simplicity of Haml and Sass, but I also have my doubts. Sass provides potentially increased functionality/flexibility in developing CSS, but Haml doesn’t provide the same increased capacity; just simplification.

    One problem with preprocessors like this is that they have potential to reduce the amount of available support for code. i.e. if your code is initially developed in Haml/Sass, and subsequently that coder moves on, then a new coder not familiar with the preprocessors is going to have difficulties.

    Also have to say that I don’t necessarily see the argument that Haml *significantly* simplifies HTML. HTML is ultimately pretty simple in layout and syntax anyway, and even though I’m familiar and comfortable with Haml, I still find HTML code much easier to read “at a glance”.

  • Akino

    HAML sounds really interesting [2]

  • http://twitter.com/jitendravyas Jitendra Vyas

    What about for Windows users?

  • http://vsegarazd.com SashaVsegarazd

    zen-coding is better

  • http://whygee.com Steve Yancharas

    I don’t care if it is cleaner, adding brain-work to html just doesn’t compute. I tried HAML, yeah it’s easier to read because there’s less code, yeah if it’s a large site it may cut down on maintenance time dramatically, but I’m sticking to my simple ways.

  • http://www.htmltohaml.com Bevan

    For anyone looking to learn HAML, check out HTMLtoHAML.com (it’s an html to haml converter). It converts HTML to HAML in real time, so it’s useful for sussing out haml’s rules.

  • https://www.youtube.com/watch?v=SQBca31lzC0 Clash Of Clans Game

    Fun Tipps für Video-Spiel, sobald ssie auf Leute über

  • http://www.bigbendweather.com/ActivityFeed/MyProfile/tabid/165/userId/3893/Default.aspx narcotics rehab

    Woah! I’m really digging the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance”
    between user friendliness and appearance. I must say you’ve
    done a very good job with this. Also, the blog loads extremely fast for me on Safari.
    Exceptional Blog!

  • http://buyarticlesonline.net/ buy cheap article

    Today, I went to the beachfront with my kids.
    I found a sea sheell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to heer ear and screamed.
    Theree was a hermit crab inside and it pinched her ear.

    She never wants to go back! LoL I knoow this iss completely off topic butt I had to tell someone!

    my website; buy cheap article

  • https://www.youtube.com/watch?v=2YRzlVoc12k Abq new listings real estate

    You really make it seem so easy with your presentation but I to find this topic to be really something which I feel I would never understand.
    It seems too complex and very huge for me. I am looking forward on your next
    publish, I will attempt to get the hold of it!

  • http://www.tiendabolaschinas.com/honi vibrador honi

    whoah this blog is wonderful i love studying
    your posts. Stay up the great work! You understand, many people
    are looking round for this information, you could help them
    greatly.

    Feel free to surf to my web-site: vibrador honi

  • http://konveksikaosmurahsurabaya.blogdetik.com/ KONVEKSI KAOS MURAH SURABAYA

    Hey there! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing a few months of hard work due to no back up.
    Do you have any solutions to protect against hackers?

  • https://www.youtube.com/watch?v=amPaG1YJWUI venta de tablets

    Pretty great post. I just stumbled upon your blog and wished to mention that I’ve really enjoyed browsing your weblog posts.
    After all I will be subscribing in your
    rss feed and I am hoping you write again soon!

    Feel free to visit my web page venta de tablets

  • http://www.elektrik.es Bicicletas electricas

    I’m not sure exactly why but this blog is loading incredibly
    slow for me. Is anyone else having this problem or is it a
    problem on my end? I’ll check back later and see if the problem still exists.

    Here is my web site :: Bicicletas electricas

  • http://usefulforgames.com/boom-beach-hack-cheats-tool Boom Beach cheats download

    Approach 3 – Extreme Coding: It is done when project requirements
    are dynamic and change frequently. The android phone was able to pull Google account pictures into the
    contact list. I think there is still huge scope available for application development in this niche.

    Look into my web blog … Boom Beach cheats download

Subscribe
Membership
About the Author