How to Set a Dynamic Class Value in Haml

If you’re transitioning from ERB to Haml in your Ruby on Rails projects, you might find yourself needing to represent dynamic values within your HTML structure. Specifically, one common scenario is setting a CSS class dynamically based on an item’s status. This blog post will guide you on how to achieve this in Haml.

The Problem

You may have a line of code like this in your ERB template:

<span class="<%= item.dashboardstatus.cssclass %>"><%= item.dashboardstatus.status %></span>

This code effectively associates the CSS class of the currently assigned status to a <span> element. When you’re trying to convert this code to Haml, it might seem a bit confusing at first. You want to ensure that the dynamic behavior remains intact while making use of Haml’s clean syntax.

The Solution in Haml

Haml simplifies views by allowing you to write less code while improving readability. To convert the line above to Haml, you can follow this approach:

%span{:class => item.dashboardstatus.cssclass}= item.dashboardstatus.status

Breaking Down the Haml Code

Let’s dissect this Haml code segment to understand how it functions:

  1. %span: This part indicates that you want to create a <span> HTML element.

  2. {:class => item.dashboardstatus.cssclass}: This is where the magic happens! This syntax sets the class attribute of the <span> using a Ruby hash. The key :class indicates that we’re setting a CSS class, and the value is dynamically fetched from the item.dashboardstatus.cssclass.

  3. = item.dashboardstatus.status: The equals sign (=) signifies that what follows should be inserted as the content of the <span>, which in this case is the value of item.dashboardstatus.status.

Why Use Haml?

Using Haml can improve your development workflow for several reasons:

  • Cleaner Syntax: Haml uses indentation to denote nesting, which leads to less clutter compared to traditional HTML.
  • Less Code: You often write fewer lines of code while achieving the same output, which makes your view files easier to read and maintain.
  • Enhanced Readability: The structure of Haml emphasizes the significance of layout and design, making it easier for developers to spot errors or understand the flow of the view.

Conclusion

Setting a dynamic class value in Haml can be accomplished with a straightforward adjustment from ERB syntax. By utilizing the hash syntax for class attributes combined with Ruby’s dynamic content insertion, you not only maintain functionality but also enhance readability.

Now that you’ve learned how to convert your ERB code, you’ll find it easier to work with Haml in your Rails applications. Embrace the change and enjoy building richly styled views with ease!