【问题标题】:Rails conditional CSS in view helper视图助手中的 Rails 条件 CSS
【发布时间】:2015-11-08 04:57:15
【问题描述】:

我有一个简单的 Rails 应用程序,我正在尝试编写一个执行以下操作的视图助手。

比较两个值。如果 current_month 金额大于预测金额,则将文本设为绿色。如果 current_month 金额小于预测金额,则将文本设为红色。

我编写了这个简单的帮助程序来将文本附加到 rails 方法的输出,但我不确定如何将 CSS/样式注入其中。

def target_hit(forecast, current)
  (if current.amount > forecast.amount
    number_to_currency(current.amount.to_s) + " Yay"
  elsif current.amount < forecast.amount
    number_to_currency(current.amount.to_s) + " No dice"
  end).html_safe
end

我非常精通后端,但在前端方面我却遇到了很多困难。任何帮助将不胜感激。

示例查看代码

<p class='total'>Current: <%= target_hit(@forecast, @current) %></p>

【问题讨论】:

  • 你可以从一个类中调用一个辅助方法。或者在您的 target_hit 方法中,您可以使用 content_tag 来定义类。我需要看看你的观点来提供一个例子。
  • @margo 我摘录了我对如何调用该方法的看法。

标签: css ruby-on-rails-4 helper


【解决方案1】:

rails helper content_tag http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag,很有用,意味着您不必使用 html_safe。我尝试将所有逻辑从视图移动到帮助器,以使视图易于阅读,例如

def target_hit(current_amt, forecast_amt)
  content_tag(:p, "#{number_to_currency(current_amt.to_s)} target_content(current_amt, forecast_amt)", class: "total #{target_class(current_amt, forecast_amt)}")
end

def target_content(current_amt, forecast_amt)
  forecast_reached?(current_amt, forecast_amt) ? "Yay" : "No dice"
end

def target_class(current_amt, forecast_amt)
  forecast_reached?(current_amt, forecast_amt) ? "green" : "red"
end

def forecast_reached?(current_amt, forecast_amt)
  current_amt >= forecast_amt
end

在视图中,你只需调用辅助方法

<%= target_hit(@current.amount, @forecast.amount) %>

【讨论】:

  • 这比我自己想出的要简单得多。我真的很喜欢这个答案。将尽快投票:)
猜你喜欢
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 2016-09-29
  • 2011-05-26
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多