link_to in helper with block

link_to in helper with block

I’m trying to get this to work:
link_to(“#”, class: “add_fields btn btn-success”) do
name
content_tag(:i, “”, :class => “icon-plus icon-white”)
end

but it only shows me the icon specified by i (twitter-bootstrap css) and not the text in name, what am I doing wrong?

Solutions/Answers:

Solution 1:

The return value of the block becomes its content. Only the last line is being returned.

You must concatenate the two strings together with + to produce a single return value:

link_to("#", class: "add_fields btn btn-success") do
  name + content_tag(:i, "", class: "icon-plus icon-white")
end

You’ll need to use html_safe to prevent the content of your tag from automatically being HTML encoded:

link_to("#", class: "add_fields btn btn-success") do
  name + content_tag(:i, "", class: "icon-plus icon-white").html_safe
end

Speaking from personal experience with Twitter Bootstrap, I know you will need a space between name and content_tag:

link_to("#", class: "add_fields btn btn-success") do
  name + ' ' + content_tag(:i, "", class: "icon-plus icon-white").html_safe
end

Alternatively, if you are inside an ERB template, you can output both values with <%=:

<%= link_to( ... ) do %>
  <%= name %>
  <%= content_tag( ... ) %>
<% end %>

Solution 2:

There are two things I’d consider:

Related:  bootstrap collapse menu disappears when resizing screen

1) The whole content of the link_to block needs to be sanitized.

link_to("#", class: "add_fields btn btn-success") do
  (name + content_tag(:i, "", class: "icon-plus icon-white")).html_safe
end

2) Can we expect input to be nil?

Things will break if we call html_safe on a nil object. Use raw if there is a chance this could happen.

link_to("#", class: "add_fields btn btn-success") do
  raw(name + content_tag(:i, "", class: "icon-plus icon-white"))
end

This is a good read on the subject. My blog post presents an interesting application of this.

Solution 3:

For those that use font-awesome or something else it might not show the icon. But this solution worked.

link_to :sort => column, :direction => direction do
   "#{title} #{content_tag(:i, "", class: "fa fa-chevron-up") }".html_safe
end

References