-
Notifications
You must be signed in to change notification settings - Fork 4
Haml Introduction
Haml is a templating language originally written by Hampton Catlin designed to be around four core principles
- Markup should be beautiful
- Markup should be DRY
- Markup should be well-indented
- HTML structure should be clear
In practice this means that Haml is a cleaner and more readable substitute for HTML. Instead of writing a template in a mix of HTML and PHP you write your template in Haml which is then compiled down to HTML and PHP for you.
We'll start by turning a single HTML tag into it's Haml equivalent.
HTML
<div>My Text</div>
Haml
%div
My Text
In Haml the percent sign (%) represents a tag. This can be any kind of tag such as %a, %ul, %img, etc. In Haml to indicate something should be contained within another element, we simply indent it another level. The snippet above indicates that "My Text" should be inside of the div.
Let's add a class to our div now!
HTML
<div class="block">My Text</div>
Haml
%div.block
My Text
In Haml we add a class to a tag by adding a period and a class name immediately after the tag name. Multiple classes can be chained together, so if I wanted to a the blue class to the div above as well I'd write %div.block.blue
.
Adding an ID to the element can be done in a similar way.
HTML
<div class="block" id="my-div">My Text</div>
Haml
%div.block#my-div
My Text
This time to add the ID we put a hash character followed by the ID. If this is starting to look somewhat familiar it's because the notation for classes and IDs in Haml has been adopted from CSS!
So what if we want to add any kind of attribute to a tag? Let's add a link into the mix
HTML
<div class="block" id="my-div">
<a href="http://example.com">My Text</a>
</div>
Haml
%div.block#my-div
%a(href="http://example.com")
My Text
In this case, the syntax is very similar to HTML, we place a set of parenthesis after the tag (and classes and ID) and we can use the same syntax for specifying an attribute as HTML.