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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay