From HTML to Haml

Sylvee
2 min readMay 2, 2017

--

What’s Haml?

I’m glad you asked. HAML is Hypertext Abstraction Markup Language. The creators of Haml designed this handy dandy tool for one sole purpose — simplify markup cleanliness, readability, and production speed.

Your HTML code in your .erb file would normally look like this:

<section class="container>
<h1><%= post.title %></h1>
<h2><%= post.subtitle %></h2>
<div class="content">
<%= post.content %>
</div>
</section>

But with the magic of Haml, your code could look like this:

%section.container
%h1= post.title
%h2= post.subtitle
.content
= post.content

What is the Syntax?

I know, I know. There are the initial feelings of denial and anger. And maybe a bit of bargaining and depression, “Come on, I need to learn another language just to write my HTML code faster?” Not a whole new language, but an abstraction of HTML. If we take a better look at Haml, it’s not really a language, but more of a collection of short keys for elements:

% Element Attributes

For any attributes in your markup, you use a % sign, attached at the front of name tag:

<section></section>                       →  %section

.Class Attributes

For your class attributes, you use a . sign:

<section class="container"></section>     →  %section.container

#Id Attributes

For your id attributes: you use a # sign:

<section class="container">               →  %section.container
<div id="wrapper"></div> → %div#wrapper
</section

How do I get Started?

What a great question! I have the answer. Start by downloading Haml gem in your terminal for your pre-existing project:

gem install haml

Voilá. Done.

Anything else?

Sure. What’s really great about Haml, is that you can also use it in your ruby projects. Haml is a drop-in replacement for ERB, meaning that any file in your app/views folder can be switched over to Haml by simply changing the extension of the file.

app/views/account/login.html.erb → app/views/account/login.html.haml

Let’s get fancy here.

<div class='item' id='item<%= item.id %>'>
<%= item.body %>
</div>

Cool, makes sense. Now with a bit of Haml magic, the code looks like this:

.item{:id => "item#{item.id}"}= item.body

Want to look at another example?

<div id='content'>
<div class='left column'>
<h2>Welcome to our site!</h2>
<p><%= print_information %></p>
</div>
<div class="right column">
<%= render :partial => "sidebar" %>
</div>
</div>

Curious what it looks like? Look below.

#content
.left.column
%h2 Welcome to our site!
%p= print_information
.right.column
= render :partial => "sidebar"

Oh, sweet, sweet Haml.

Moar Reading

Haml Documentation — http://haml.info/

--

--