This post has been more than 5 years since it was last updated.
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.
Add gems "haml-rails" and run
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:
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:
<h1>Welcome To The Show</h1>
%h1= "Welcome To The Show"
% at the beginning, folloewd by the tag's name, you'll never have to close the tag again
<% @notes.each do |note| %> <h2><%= note.title %></h2> <p><%= note.content %></p> <% end %>
- @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
You don't even need to write the name's tag
div but just use the
%, and Haml will do the rest.
<div class="header"> <div class="wrapper"> <%= @course.teacher %> </div> </div>
.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
<section class=”container”> <h1><%= post.title %></h1> <h2><%= post.subtitle %></h2> <div class=”content”, id="post_content"> <%= post.content %> </div> </section>
%section.container %h1= post.title %h2= post.subtitle .content#post_content = post.content
Haml can be pretty hard at the beginning when you close to it, you'll find it efficiency.
All Rights Reserved