Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 793
wintersolutions Avatar asked Jul 03 '12 18:07

wintersolutions


3 Answers

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 %>
like image 119
meagar Avatar answered Nov 14 '22 08:11

meagar


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.

like image 30
Jan Klimo Avatar answered Nov 14 '22 06:11

Jan Klimo


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
like image 1
Petros Kyriakou Avatar answered Nov 14 '22 07:11

Petros Kyriakou