Rails 根据条件在 html 代码上包装 link_to
Rails wrap link_to on html code based on condition
是否有一种简洁的语法可以根据条件将 link_to 包装在 html 代码上?因为DRY,我不想重复相同的代码。
<% if condition? %>
<%= link_to bla_bla_path do %>
<p>Some html here</p>
<% end %>
<% else %>
<p>Some html here</p>
<% end %>
我知道有 link_to_if 但它没有 else
部分 :(((
link_to_if
要通过的障碍实际上是else
。仔细查看您链接到的文档。
无论如何,使用 link_to_if
也无法解决您的干燥问题。你想要做的是使用 capture 将公共 html 分配给变量:
<% content = capture do %>
<p>Some html here</p>
<% end %>
<% if condition? %>
<%= link_to bla_bla_path do %>
<%= content %>
<% end %>
<% else %>
<%= content %>
<% end %>
是否有一种简洁的语法可以根据条件将 link_to 包装在 html 代码上?因为DRY,我不想重复相同的代码。
<% if condition? %>
<%= link_to bla_bla_path do %>
<p>Some html here</p>
<% end %>
<% else %>
<p>Some html here</p>
<% end %>
我知道有 link_to_if 但它没有 else
部分 :(((
link_to_if
要通过的障碍实际上是else
。仔细查看您链接到的文档。
无论如何,使用 link_to_if
也无法解决您的干燥问题。你想要做的是使用 capture 将公共 html 分配给变量:
<% content = capture do %>
<p>Some html here</p>
<% end %>
<% if condition? %>
<%= link_to bla_bla_path do %>
<%= content %>
<% end %>
<% else %>
<%= content %>
<% end %>