DEV Community

Ankit Pariyar
Ankit Pariyar

Posted on • Updated on

Conditional CSS Classes in Rails with class_names

Managing dynamic CSS classes in Rails views can get messy with string concatenation and conditional logic. The class_names method, simplifies this by letting you conditionally build class lists in a clean, readable way.

class_names("btn", "btn-primary", { "btn-disabled": disabled? })
Enter fullscreen mode Exit fullscreen mode

If disabled? is true, this outputs:

class="btn btn-primary btn-disabled"
Enter fullscreen mode Exit fullscreen mode

Otherwise, it excludes the "btn-disabled" class. This eliminates messy conditionals, making your views easier to read and maintain.

Top comments (1)

Collapse
 
r10rivas profile image
Roberto Rivas

Nice!