Rails: How can I show a block with or without a link based on a condition (link_to_if)

≯℡__Kan透↙ 提交于 2019-12-05 04:39:53

I wrote my own helper for this:

   def link_to_if_with_block condition, options, html_options={}, &block
     if condition
       link_to options, html_options, &block
     else
       capture &block
     end
   end

You can use it like this:

<%= link_to_if_with_block true, new_model_path { "test" } %>
<%= link_to_if_with_block true, new_model_path do %>
  Something more complicated
<% end %>

I just overwrote the built in method cause the block use they offer really doesn't make much sense for our use. Just add it to a helper and this will make link_to_if work just like link_to.

def link_to_if(*args,&block)
  args.insert 1, capture(&block) if block_given?

  super *args
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!