Allow hash for conditional class attribute in tag helper

When dealing with conditional class attribute values in HTML tags, I often find myself writing code like:

link_to(post.title, post, class: “post #{post.active? ? “active” : “”}”)

The code would be much cleaner if we allowed a hash syntax:

link_to(post.title, post, class: {“post” => true, “active” => post.active?})

The implementation is straightforward:

https://github.com/sos4nt/rails/commit/a9ed04f75ce9db46af6cbdefa64dfb09fb3eb73a

What do you think?

-Stefan

-1

I don’t see why ‘class’ would get the special treatment when all other attributes could be candidates too and that style is very inconsistent with pretty much all of rails and not particularly clear either.

I personally just use a helper if logic is required for attributes.

Agreed.

could you provide an example of one of those helpers?

You can pass Arrays to the class: option and it will do what you expect it to:

link_to(post.title, post, class: [“post”, “active” if post.active?])

Cheers,

-foca

That array syntax is invalid.

I think the class attribute is quite unique because it’s a space-separated list. Are there any other attributes like that?

Here’s a very simple example.

def link_to_post(post)

html_class = ["post"]

html_class << "active" if post.active?

link_to(post.title, post, class: html_class)

end

Sorry, it should be [“post”, post.active? && “active”]

Or wrap with ():

link_to(post.title, post, class: [“post”, (“active” if post.active?)])

They are not equivalent. One will return false and the other nil.

If you really need it just override the link_to and add this syntax you want to use

def link_to

class_attr = deal_with_classes_the_way_i_want

super(stuff, class: class_attr)

end

Well this is old, but still relevant :slight_smile: I’ve seen the replies, but i’ve we do it the way we wanted and just because all the other attributes are doing it that way, i think you’re doing it wrong. Rails is meant to please the developer, making painful constructs just to make a link selected or current is just crazy.

I’d would love it if rails would have a class: {selected: selected?, btn: true}

Rails, is elegant, makes sense and just works. Some hashes get special treatment, thats fine.

:class should be one of them.

To reiterate a post I made on a related topic

Rather than alter all the individual helper methods which take a :class option (e.g. link_to, content_tag), why not just use a helper method to generate the finalized list of classes?

For example,

link_to “Hello”, root_url, class: class_set(selected: selected?, btn: true)

There’s an existing gem which was inspired by React’s classSet and exposes this exact functionality:
https://github.com/nLight/css-class-string