【问题标题】:Rails helper in view - How to have the result of a helper rendered?Rails helper in view - 如何渲染助手的结果?
【发布时间】: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


    【解决方案1】:

    为了实际呈现 HTML,您需要使用 html_safe

    = amountColor(item.amount).html_safe
    

    您也可以只内联它并完全消除对助手的需求:

    - klass = item.amount.positive ? 'positive' : 'negative'
    %span{class: klass}= item.amount
    

    【讨论】:

    • 我知道这很简单!谢谢;)
    • 添加了一个关于内联赋值的小补充
    猜你喜欢
    • 2011-03-20
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 2012-01-31
    • 2011-12-11
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多