Rails default templating language is ERB which embeds ruby code into a HTML document, but there is an alternative templating language available called HAML.
HAML(HTML abstraction markup language) provides an elegant syntax which is easy to understand and maintain, it shows the DOM hierarchy of a document.
In ERB we embed the ruby code between <% ruby code %> delimiters whereas HAML eliminates <% %> and use indentation for the beginning and end of markup so that closing tags are not required.
In order to use HAML in Rails project first we need to install HAML by simply adding Haml into Gemfile..
gem 'haml'
And run the gem bundler command:
$ bundle install
Now if we want to use Haml there is no need to modify the application.rb file. Because when Rails application loads, Haml will be loaded. Also if we generate a scaffold, we’ll get Haml instead of ERB templates.
Let’s convert some basic ERB into Haml
ERB
<span><%= @article.title %></span>
Haml
%span= @article.title
As you can see in Haml we write a tag by using the percent sign and then the name of the tag. Here after the tag name = is used, which tells Haml to evaluate Ruby code and then print the value. Haml automatically detects newlines in the return value and format the tag properly.
HTML
<span class="code" id="message">Hello, World!</span>
Haml
%span{:class => "myclass", :id => "new_message"} Hello, World!
OR
%span.myclass#new_message Hello, World!
In the example above both the Haml line will produce the same code.As you can see class name is replaced with a . and id is replaced with #, also we have not used = so it will be interpreted as a normal string not as a Ruby code.
HTML
<div class='myclass'>Hello, World!</div>
Haml
.myclass Hello, World!
Here in Haml we have not used div tags as it will take default to %div.
ERB
<div class='myclass' id='myarticle<%= @article.id %>'>
<%= @article.title %>
</div>
Haml
.myclass{:id => "myarticle#{@article.id}"}= @article.title
Here in Haml nesting is done by using whitespace.
ERB
<div id='myarticle'>
<div class='myclass title'>
<h2>Hello World</h2>
<p><%= @article.title %></p>
</div>
<div class="myclass myclass">
<%= render :partial => "myclass" %>
</div>
</div>
Haml
#myarticle
.myclass.title
%h2 Hello World
%p= @article.title
.myclass.myclass
= render :partial => "myclass"
In Haml - symbol is used to evaluate something as a ruby code but unlike = it will not print the value.
For Example
Haml
- if current_user
= link_to 'Logout', logout_path
- else
= link_to 'Login', login_path
0 Comment(s)