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!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay