Rails wrap link_to on html code based on condition

truongnm

New Member
#1
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.
Mã:
<% 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 :(((
 

Admin

Administrator
Thành viên BQT
#2
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:

Mã:
<% content = capture do %>
  <p>Some html here</p>
<% end %>

<% if condition? %>
  <%= link_to bla_bla_path do %>
    <%= content %>
  <% end %>
<% else %>
  <%= content %>
<% end %>
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top