Question

How can I use the same block of the link_to_unless when condition is true (in place of 'Hello' in the example) without write the block two times (with an if ... else)?

<%= link_to_unless(url.nil?, 'Hello') do %>
  <%= image_tag(image_url) %>
  <h1><%= title %></h1>
  <h2><%= subtitle %></h2>
<% end %>

I would like to have this if url exists

<a href="url">
  <img src ... />
  <h1>...</h1>
  <h2>...</h2>
</a>

and the same content without the link if url is nil

<img src ... />
<h1>...</h1>
<h2>...</h2>
Was it helpful?

Solution

You could actually create an helper method like this

In your application_helper.rb:

def conditional_link(options={}, &block)
    unless options.delete(:hide_link)
        concat content_tag(:a, capture(&block), options)
    else
        concat capture(&block)
    end
end

And in your view:

<% conditional_link(:hide_link => url.nil?, :href => "/hello" ) do %>
    <%= image_tag(image_url) %>
    <h1><%= title %></h1>
    <h2><%= subtitle %></h2>
<% end %>

Assuming that your url.nil? does work properly by returning a boolean

You can of course pass more options to your link, for example a class or id:

<% conditional_link(:hide_link => url.nil?, :href => "/hello", :class => "myclass", :id => "myid" ) do %>
    <%= image_tag(image_url) %>
    <h1><%= title %></h1>
    <h2><%= subtitle %></h2>
<% end %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top