简体   繁体   English

如何将块传递给助手返回的“ link_to”?

[英]How can I pass a block to a 'link_to' returned from a Helper?

I think this one is a little hard to explain by the title alone, so here's some I code I came up with: 我认为仅凭标题很难解释这个问题,因此我想出了一些我编写的代码:

Rails View Helper Rails视图助手

module SplashHelper

  def send_link_or_tag(link=true)
    if link
      link_to nil, root_path, class: 'to-block'
    else
      content_tag :div, 'The content'
    end
  end
end

View (haml) that uses the Helper 使用助手的视图(haml)

- 5.times do |i|
  - if i%2 == 0

    = send_link_or_tag do
      -#THE PROBLEM IS THAT I CAN'T ADD CONTENT TO THE
        RETURNED link_to (<a> tag) in this case the <p> tag
        INSIDE THIS BLOCK!
      %p = 2 + 2 

  - else

    = send_link_or_tag false do
      -# SAME PROBLEM HERE.
      %p = 3 * 3

In summary, the Helper successfully returns a link_to or a content_tag , but I need to keep concatenating or adding more tags inside the tag returned by the Helper ( through a block ). 总而言之,Helper成功地返回了link_tocontent_tag ,但是我需要继续在Helper返回的标签内( 通过一个块串联添加更多标签。 It seems this should be easy to do in Rails, What am I missing? 似乎在Rails中应该很容易做到,我想念的是什么?

Thanks in advance! 提前致谢!

Try this for your helper method, 试试这个作为您的辅助方法,

def send_link_or_tag(link=true)
  if link
    link_to root_path, class: 'to-block' do
      yield
    end
  else
    content_tag :div do
      yield
    end
  end
end

This will yield the content in an a or div tag from the block defined in your view. 这将从视图中定义的块中的adiv标签中产生内容。

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

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