简体   繁体   English

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? 但它只能说明我所指定的图标i (Twitter的引导CSS),而不是在文本name ,我究竟做错了什么?

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: 您需要使用html_safe来阻止标记内容自动进行HTML编码:

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 : 根据Twitter Bootstrap的个人经验,我知道你需要在namecontent_tag之间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 <%= : 或者,如果您在ERB模板中,则可以使用<%=输出两个值:

<%= 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. 1)需要对link_to块的全部内容进行清理。

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 ? 2)我们可以期望输入nil吗?

Things will break if we call html_safe on a nil object. 如果我们在一个nil对象上调用html_safe ,事情就会破裂。 Use raw if there is a chance this could happen. 如果有可能发生这种情况,请使用raw

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. 对于那些使用font-awesome或其他东西的人来说,它可能不会显示图标。 But this solution worked. 但这个解决方案有效。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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