Stop! Haml Time!
NOV
23
2008
Ok, first of all I have to apologize for the title of this post, but I couldn't resist the pun.
Anyway, as the title suggests, I've recently converted all of my erb pages on this site to haml. Haml is a DSL templating language uses to generate well-formed XHTML. The documentation site claims that you can become familiar with the syntax in about 20 minutes. I think, as long as you already know XHTML, you can pick it up in about 10 minutes. The concept is pretty simple. Each tag should be on its own line, and everything contained in that tag should be indented below it. If a tag doesn't have any other tags contained in it, then the content can be on the same line as the tag. Also, div is the default tag, so you can just pass an id or class name to output a div.
%p This is a paragraph tag.
%ul
%li First list item
%li Second list item
#id_name Content in div
.class_name Content in div
Will convert to (with beautiful formatting):
<p>This is a paragraph tag.</p>
<ul>
<li>First list item</li>
<li>Second list item</li>
</ul>
<div id="id_name">
Content in div
</div>
<div class="class_name">
Content in div
</div>
It's really easy to include rails evaluation and output blocks too.
- @posts.each do |post|
%p
Written by
= post.author
%p= post.date
Notice that there is no need for end when a block is done. When haml sees that the indentation has ended, it automatically ends the block.
You can also pass any attributes to an HTML tag via a ruby hash.
%img{:src => "/images/picture.png", :alt => "Picture", :title => "Picture"}
I think the coolest thing about Haml is how it can assign a class and unique id to an element simply by passing an ActiveRecord object within square brackets.
%div[@post]
Will output:
<div class="post" id="post_18"><div>
If you'd like to learn more, you can take a look at the online documentation, or you can look at the code for my site on Github.
Leave a comment:
Links
Archives
© 2008 Travis Roberts. All rights reserved.