The Sweet Spot
On software development, engineering leadership, machine learning and all things shiny.

HAML object references

Did you guys know that you can use the ‘[ ]’ brackets in HAML to automatically set the id and class on a tag, kind of like Rails’ tag helper?

1
2
3
4
5
6
7
8
9
10
11
# file: app/controllers/users_controller.rb

def show
  @user = CrazyUser.find(15)
end

-# file: app/views/users/show.haml

%div[@user, :greeting]
  %bar[290]/
  Hello!

is compiled to:

1
2
3
4
<div class='greeting_crazy_user' id='greeting_crazy_user_15'>
  <bar class='fixnum' id='fixnum_581' />
  Hello!
</div>

Keeps things nice, concise and DRY. See the HAML documentation.

Liking what you read?

Accelerate your engineering leadership by receiving my monthly newsletter!

    At most 1 email a month. Unsubscribe at any time.