Tag: HAML

Templates in HAML. Using a gem.

Templates in HAML. Using a gem.

So far I used the default templating which is ERB. ERB is considered verbose, there is a lot of opening ERB tags and then closing them etc. Have a look at verbs views:

ls app/views/verb/

index.html.erb show.html.erb

ERB allows you to embed Ruby code into the HTML code. But there is a quite interesting way, more Ruby way of writing templates and it’s called HAML. It favors simplicity, replaces id= with #, class = with . so it looks like a css file.

But the main question is: how to use it since it is not in Rails 5 by default? If we replace the code inside the page index to match HAML and replace the extension?

$ cat app/views/page/index.html.erb 
<h1>Here are the verbs you can learn so far</h1>
<% @verbs.each do |v| %>
<p><%= v.infinitive %></p>
<% end %>
<h1>Here are some adjectives you can learn so far</h1>
<% @adjectives.each do |a| %>
<p><%= a.base %></p>
<% end %>

Becomes:

%h1 Here are the verbs you can learn so far
- @verbs.each do |v|
  %p -  v.infinitive 
- end 
%h1 Here are some adjectives you can learn so far
- @adjectives.each do |a| 
  %p - a.base 
- end

As you can see the code is cleaner, it respects double space indentation to mark the nesting items. Last but not least replace the file extension:

 mv   app/views/page/index.html.erb app/views/page/index.html.haml

Try to run the sever again and you get the error of the day. ‘Unknown format’. Who could expect that? To remedy this I need to install the gem – library – that will enable .haml files reading. Haml page says: add it to your Gemfile. So I added it just above the group:development section:

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
gem 'haml'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

Now run bundle. Stop Rails server if you haven’t done so already. Run it again.

It should work. But it does not.  It is because haml does not require the ‘end’ keyword, which is nice. So we end up with a clean template:

<h1>Here are the verbs you can learn so far</h1>
- @verbs.each do |v| 
 %p - v.infinitive
<h1>Here are some adjectives you can learn so far</h1>
- @adjectives.each do |a| 
 %p - a.base

But what is amazing about using HAML is that it does not exclude using ERB! As of now I have only a single template in .haml and all the rest in .erb

Git status shows it all: modified Gemfile, removed .erb file and created .haml. Commit.

git status
On branch master
Changes to be committed:
 (use "git reset HEAD <file>..." to unstage)

modified: Gemfile
 modified: Gemfile.lock
 deleted: app/views/page/index.html.erb
 new file: app/views/page/index.html.haml