Search code examples
htmlruby-on-railsrubylink-to

Rails wrap link_to on html code based on condition


Is there a clean syntax to wrap link_to on html code based on condition? Because DRY, I don't want to repeat the same code.

<% if condition? %>
  <%= link_to bla_bla_path do %>
    <p>Some html here</p>
  <% end %>
<% else %>
  <p>Some html here</p>
<% end %>

I know there is link_to_if but it don't have the part else :(((


Solution

  • With link_to_if the block to pass is actually the else. Have a closer look at the documentation you linked to.

    Anyway, using link_to_if won't solve your dryness issue either. What you want to do is using capture to assign the common html to a variable:

    <% content = capture do %>
      <p>Some html here</p>
    <% end %>
    
    <% if condition? %>
      <%= link_to bla_bla_path do %>
        <%= content %>
      <% end %>
    <% else %>
      <%= content %>
    <% end %>