【问题标题】:Rails wrap link_to on html code based on conditionRails 根据条件在 html 代码上包装 link_to
【发布时间】:2018-10-12 14:37:22
【问题描述】:

是否有一种简洁的语法可以根据条件将 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 :(((

【问题讨论】:

  • 你可以创建一个助手来保持它干燥。 condition 会是什么样子?
  • 你的意思是你不需要使用else或者你只是不明白如何使用它?
  • 我要使用else

标签: html ruby-on-rails ruby link-to


【解决方案1】:

对于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 %>

【讨论】:

    猜你喜欢
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多