Ruby 三元中的 link_to

Ruby ternary in a link_to

我的基本问题是如何使用三元将其转换为一行代码?

 <% if tip_off %>
  <%= link_to "Dead Man's Snitch", [:homepage], class: "topbar-brand-tip-off", rel: "home" %>
<% else %>
  <%= link_to "Dead Man's Snitch", [:homepage], class: "topbar-brand", rel: "home" %>
<% end %>

我所做的只是在特定情况下更改 class 名称。

我觉得分两行更易读

<% link_class = tip_off ? "topbar-brand-tip-off" : "topbar-brand" %>
<%= link_to "Dead Man's Snitch", [:homepage], class: link_class, rel: "home" %>

通过插入 class 值:

<%= link_to "Dead Man's Snitch", [:homepage], class: "topbar-brand#{tip_off ? '-tip-off': ''}", rel: "home" %>

您可以在 link_to 之外进行:

<% css_class = tip_off ? "topbar-brand-tip-off" : "topbar-brand" %>
<%= link_to "Dead Man's Snitch", [:homepage], class: css_class, rel: "home" %>

或者你可以用插值法

<%= link_to "Dead Man's Snitch", [:homepage], class: "topbar-brand#{'-tip-off' if tip-off}", rel: "home" %>

您可以使用内置于 link_to_if

中的 rails
 link_to_if(tip_off, "Dead Man's Snitch", { [ACTION_OPTIONS] }, class: "topbar-brand-tip-off") do
    link_to("Dead Man's Snitch", { [ACTION_OPTIONS] }, class: "topbar-brand") 
 end

文档:http://apidock.com/rails/v4.2.1/ActionView/Helpers/UrlHelper/link_to_if