如何根据也传递给它的另一个变量的值将特定字符串传递给我的部分?

How do I pass a specific string to my partial depending on the value of another variable also being passed to it?

我有以下部分 (_card_brand.html.erb),看起来像这样:

<div class="payment-card">
    <i class="fa fa-cc-<%= brand.downcase %> payment-icon-big text-success"></i>
</div>

使 HTML 看起来像这样:

<div class="payment-card">
    <i class="fa fa-cc-visa payment-icon-big text-success"></i>
</div>

上面是这样渲染的:

<%= render partial: "subscriptions/card_brand", locals: { brand: current_user.card_brand } %>

我想做的是将 class text-success 更改为: text-warning, text-primary, text-danger, etc. 取决于卡是否具有 brand: visa, amex, mastercard, discovery, etc.

所以:

  • Visa = Success
  • AMEX = Warning
  • Mastercard = Primary
  • Discovery = Danger

任何其他卡片都是其他 classes.

如何在我的视图中优雅地呈现部分内容?

您可以创建一个助手并使用它,这样也可以轻松添加新的 类。

application_helper.rb

CARD_CLASS = {
  'visa' => 'success',
  'amex' => 'warning',
  'mastercard' => 'primary',
  'discovery' => 'danger'
}

def payment_class(type)
  CARD_CLASS[type.downcase]
end

_card_brand.html.erb

<div class="payment-card">
    <i class="fa fa-cc-<%= brand.downcase %> payment-icon-big text-text-<%= payment_class(brand.downcase) %>"></i>
</div>