Robert Hirsch
Robert Hirsch

Reputation: 91

Adding classes to content_tag in Rails

I want to add a class to the (:i) tag inside the Rails code:

<td><%= link_to content_tag(:i), item %></td>

I want the final code to look like:

<td><a href="/items/2"><i class="#"></i></a></td>

Upvotes: 2

Views: 8482

Answers (2)

Jim Deville
Jim Deville

Reputation: 10662

@Dogbert is correct, except that you need to pass nil as the second parameter, since content_tag is defined as

def content_tag(tag, content_or_options_with_block=nil, options=nil, escape=true, &block)
  ...
end

The second parameter is only considered content if you pass block. To expand on it, any extra options passed in at that point will become HTML attributes, so the same form applies to things like IDs, data-*, etc.

content_tag(:i, nil, class: '#', id: 'foo', data: {foo: 'bar'})

will become

<i class="#" id="foo" data-foo="bar"></i>

Upvotes: 18

Anil Maurya
Anil Maurya

Reputation: 2328

Try This

<%= link_to content_tag(:i, :class => '#'), item %>

Upvotes: 1

Related Questions