8

I have a complex block of tags (<h3>, <p>, ...) that I want to render with a link or without a link around it based on a condition.

I know about link_to_if that works like that:

<% link_to_if condition, name, path %>

if the condition is false only the name will be rendered.

And I know about the link_to with &block:

<% link_to path do %>
  [complex content]
<% end %>

I want a combination of both. A link_to_if statement that accepts a &block, so that the block will be rendered without a link around it, if the condition is false. Unfortunately the link_to_if statement with a &block works not like the link_to statement :(

Does anyone have suggestion for me? Any help is highly appreciated

DiegoFrings
  • 3,043
  • 3
  • 26
  • 30

2 Answers2

23

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 %>
klump
  • 3,259
  • 2
  • 23
  • 26
  • I just do not know how it works out with passing on all the different arguments to `link_to`, but I guess when you need something more sophisticated you will figure it out ;) – klump Apr 25 '12 at 16:20
  • Hmmm. Something is odd with your helper method. If I use the Helper with `<%= %>` the block will be rendered once (with a link around it) if condition is true, but twice (wihtout a link) if the condition is false :( – DiegoFrings Apr 26 '12 at 15:58
  • 1
    `capture(&block)` instead of `block.call` does the job :) – DiegoFrings Apr 26 '12 at 16:08
4

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
Paul Alexander
  • 31,970
  • 14
  • 96
  • 151