【发布时间】:2021-04-11 19:56:46
【问题描述】:
这是我关于 Rails 的第一个问题。我只探索了一个月。
在一个视图中,我有一个非常简单的条件来应用一个数字,以决定用span 将其包装为.negative 或.positive 类(使其变为红色或绿色)。
下面的代码可以工作...但是要经常重复使用。
.col-3
- if item.amount.positive?
%span.positive
= item.amount
- else
%span.negative
= item.amount
所以为了保持 DRY,我想让它成为application_helper.rb 中的“帮手”。我找到了这个How to use Haml in your helpers,并写了一个helper,如下:
def amountColor(x)
puts "============================================"
- if x.positive?
puts "POSITIVE"
render_haml <<-HAML, amount: x
%span.positive= amount
HAML
else
puts "NEGATIVE"
render_haml <<-HAML, amount: x
%span.negative= amount
HAML
end
puts "============================================"
end
我尝试这样称呼它:
.col-3
-amountColor(item.amount)
Nothing displays just above this line.
在服务器的控制台中,我得到:
Rendering pages/home.html.haml within layouts/application
============================================
NEGATIVE
<span class='negative'>-100</span>
============================================
Rendered pages/home.html.haml within layouts/application (Duration: 1.8ms | Allocations: 1856)
Rendered layout layouts/application.html.haml (Duration: 2.6ms | Allocations: 2379)
Completed 200 OK in 27ms (Views: 3.5ms | ActiveRecord: 2.1ms | Allocations: 13435)
这让我觉得助手被调用并且它的工作非常正确......但是 span 没有呈现。
现在如果我尝试(= 而不是-):
.col-3
= amountColor(item.amount)
它将span 呈现为文本...
【问题讨论】:
标签: ruby-on-rails ruby haml