DEV Community

Ankit Pariyar
Ankit Pariyar

Posted on • Edited on

1

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!

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay