0

Using Haml with Rails

I. Introduction:

Haml is an useful tool to keep the work clean and organized. That why today, I want to introduce how to use Haml in a new Rails project and how to integrate into an existing project.

II. Installation:

Add gems "haml-rails" and run bundle install

Gemfile

gem "haml-rails"

Convert the erb layout file by running this command:

rails generate haml:application_layout convert

You can also converting all .erb views to haml by:

rake haml:erb2haml

Beside converting .erb file, this command will give you option to replace existing haml file or keep it in place.

III. Using Haml:

Here some example to show how Haml help to simplify your markup and speed up front-end development:

1. Tags:

.erb

<h1>Welcome To The Show</h1>

.haml

%h1= "Welcome To The Show"

By using % at the beginning, folloewd by the tag's name, you'll never have to close the tag again

2. Loops:

.erb

<% @notes.each do |note| %>
    <h2><%= note.title %></h2>
    <p><%= note.content %></p>
<% end %>

.haml

  • @notes.each do |note| %h2= note.title %p= note.content

For ruby code, you just have to put = and don't need <% end %> blocks to close

3. Divs

You don't even need to write the name's tag div but just use the %, and Haml will do the rest.

.erb

<div class="header">
    <div class="wrapper">
        <%= @course.teacher %>
    </div>
</div>

.haml

.header
    .wrapper
        = @course.teacher

4. Adding attributes:

We already have some attributes examples, but I will write it more clearly. You can define in the the similiar way with CSS

.erb

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

.haml

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

IV. Conclusion

Haml can be pretty hard at the beginning when you close to it, you'll find it efficiency.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí