简体   繁体   中英

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?

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 %>

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM