19

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?

3 Answers 3

30

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 %>
3
  • if im doing this my button shows: foo<i class="icon-plus icon-white"></i> Jul 3, 2012 at 18:44
  • You can use HTML safe to mark your strings as not requiring HTML encoding.
    – user229044
    Jul 3, 2012 at 18:54
  • 4
    I did test it with html_safe too and it didnt work, but this works: link_to("#", class: "add_fields btn btn-success") do (name + ' ' + content_tag(:i, "", :class => "icon-plus icon-white")).html_safe end if you want you can update your answer, thank you very much! Jul 3, 2012 at 19:06
2

There are two things I'd consider:

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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.