HAML and Rails View Helpers

I hit another little snag last night with HAML.  Take a look at this page:

formYou can see that the bootstrap formatting on the second form input is wrong and the page is rendering a default html form.  The first form is working right.  Here’s the HAML:

form code

The correct code is on lines 8 and 9.  The incorrect code is on lines 11 and 12. This is something that is obvious once you understand it, but not so obvious at first.  With HAML, you can create a class for a div by typing

.className

So it seems like if you want to create a text box input, you could just type

.form-control

But what this actually does is create a div with the class “form-control”:

incorrect html

The input is created without a class within that div. Thus, a plain html input box.

form_for, .label,  and other rails view helpers are Ruby code that generate HTML. So you have to prefix them like so, with the class declaration within the attributes hash:

=f.text_field :first_name, class: "form-control"

Like I said, obvious once you understand it. But it took me a while to figure out.

Building an Index Page with HAML

HAML is a simple templating language for Ruby. I finally decided to pick it up today.

I started with one of the simplest views in my rails app, an index page that lists all employees. Here’s the original code, in erb:

erb index

And here’s what I came up with in Haml:

haml

The thing to notice here is that I had to create new divs for each bit of Ruby code.

 .row
 .col-md-3= e.full_name link_to "Edit", edit_employee_path(e) link_to "Delete", e, method: :delete

just won’t work in HAML. Which is fine, but it took me a little while to figure it out. Most of the tutorials I found didn’t really explain this, and the reference didn’t have any examples of how to put multiple lines of Ruby into a div either. Turns out it’s because you can’t, apparently.

Overall I’m finding HAML to be really nice.  It’s simple, quick to pick up (20 minutes for the basics, seriously), and cuts down on typing quite a bit.