HAML

Learning preprocessors is always a good thing to do, it might shorten your work, you become more efficient. HAML is a preprocessor for HTML and it stands for HTML Abstraction Markup Language. The main idea is to write less, code more. Let’s dive in deep:

The tags are prefixed with the % mark the attributes are surrounded with { }, attribute probperties are prefixed with : and the values with => and the attributes are divided with a , sign.

   %h2 This Is a Headline
   %p 
       %a{:href => "www.google.com", :title => "this link goes to google"}
           This is a paragraph. 
   %ul
       %li List item one
       %li List item two
       %li List item three

This results:

   

This is a Headline

This is a paragraph.

  • List item one
  • List item two
  • List item three

Note: Indenting is crucial and it declares hierarchy. If you indent more or less then it throws an error. Not specifying a tag, results in a default div tag, so the usage of %div is unnecessary.

You can also use id or class attributes just like this:

    %p.item 
       Hello
    #content
       content text

Now that we know some basic stuff about HAML, let’s do something more advanced. Let’s generate a long list from an array to shorten writing:

    %ul  
      - ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7'].each do |name|
        %li{:class = name}
        = t("itemgroup.items.#{name}_html")  

The result:

  • About us
  • What we do
  • Our team
  • Our portfolio
  • Events
  • Testimonies
  • Contact

It’s almost like javascript. We have an array ( [ ] ) with items separated with comma, then we iterate through it with the each do method and define a handler |name| for further reference. Then we use that |name| variable for the classname. In the last line we have an example for internationalization the =t() getting the data from the object that is stored in the controller.

This was an example for iteration but let’s do a loop with defined number of times.

  - 6.times do |name|
    %p{:class => name}

That’s it folks for now, I will come back with more goodies in the next articles. Till then go out, breath in fresh air.