Using Stimulus with Haml or Slim

Learn about Haml and Slim in this lesson.

We'll cover the following

Since Stimulus depends so much on HTML attribute names, you might wonder how Stimulus works in HTML replacement tools like Haml and Slim.

Haml generally treats attribute lists as Ruby hashes, so you can do this:

%section.day-body{"data-controller": "day-toggle",
  "data-day-toggle-active": "false",
  "data-day-toggle-class-name": "is-hidden"}>

You need the quotation marks around the attribute names because Ruby symbol literals can’t include dashes, so just data-controller: "day-toggle" is a syntax error.

You can simplify the attribute names slightly by nesting the hash:

%section.day-body{data: {controller: "day-toggle",
  "day-toggle-active": "false",
  "day-toggle-class-name": "is-hidden"}}>

This version automatically prefixes each of the sub-hash keys with data, so you’ll get the same attributes in the end with slightly less typing. One Haml quirk is that you can only legally include the line break after a comma, not just on an open brace, so the first line of a nested hash like this can get long.

Slim lets you use the attributes directly without building a Ruby hash, so no commas, and a slightly different syntax:

section.day-body(data-controller="day-toggle"
  data-day-toggle-active="false"
  data-day-toggle-class-name=is-hidden)>

As much as I want to, I don’t think I can put the data-controller attribute on a new line and have the first line end in just the open parenthesis.

The value of the attribute can be a hash, in which case you get the same prefix behavior, so this is the same result:

section.day-body(data={controller:"day-toggle", 
  "day-toggle-active": "false"
  "day-toggle-class-name": "is-hidden"}>

You can also use Slim’s splat sequence to use a Ruby hash directly:

%section.day-body*{"data-controller": "day-toggle",
  "data-day-toggle-active": "false",
  "data-day-toggle-class-name": "is-hidden"}>

I don’t have a strong opinion on the best syntax here. I did a biggish Stimulus project using Haml mostly in the second style, and it was fine except for some long lines where there were multiple controllers or something on an attribute.

What’s next?

Stimulus is a small framework that can easily be used for relatively simple JavaScript interactions. There are some structural tricks and idioms that we’ll get into in later chapters as we try some more complex interactions.

First, though, let’s look at a bigger library, React, and see what it can do for us in our Rails application.

Get hands-on with 1400+ tech skills courses.