Read more

Haml: Generating a unique selector for an element

Henning Koch
July 14, 2018Software engineer at makandra GmbH

Having a unique selector for an element is useful to later select it from JavaScript or to update a fragment with an Unpoly Show archive.org snapshot .

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Haml lets you use square brackets ([]) to generate a unique class name and ID from a given Ruby object. Haml will infer a class attribute from the given object's Ruby class. It will also infer an id attribute from the given object's Ruby class and #id method.

This is especially useful with ActiveRecord instances, which have a persisted #id and will hence generate the same selector over multiple renderings of the same view.

Example

- @users.each do |user|
  .row[user]
    = user.name

This compiles to:

<div class='user row' id='user_37'>Alice</div>
<div class='user row' id='user_38'>Bob</div>

Since the record's #id is part of the generated selector, it will be the same over multiple renderings of the same view.

Controlling the generated string

By default Haml will downcase and underscore the class name. So ForumPost will become forum_post.

You can control the generated string by overriding the #haml_object_ref method in the referenced object:

class ForumPost < ActiveRecord::Base

  def haml_object_ref
    'forum-comment'
  end
  
end
Posted by Henning Koch to makandra dev (2018-07-14 07:47)