haml_tag直接输出到Haml模板

ran*_*its 8 ruby haml ruby-on-rails

我的HAML模板的帮助器我做错了什么?

  def display_event(event)
    event = MultiJson.decode(event)
    markup_class = get_markup_class(event)
    haml_tag :li, :class => markup_class do
      haml_tag :b, "Foo"
      haml_tag :i, "Bar"
    end
  end
Run Code Online (Sandbox Code Playgroud)

这是错误:

haml_tag outputs directly to the Haml template.
Disregard its return value and use the - operator,
or use capture_haml to get the value as a String.
Run Code Online (Sandbox Code Playgroud)

模板调用display_event,如下所示:

 - @events.each do |event|
     = display_event(event)
Run Code Online (Sandbox Code Playgroud)

如果我使用常规标记,它将扩展到以下内容

%li.fooclass
   %b Foo
   %i Bar
Run Code Online (Sandbox Code Playgroud)

mat*_*att 12

错误消息中的线索:

Disregard its return value and use the - operator,
or use capture_haml to get the value as a String.
Run Code Online (Sandbox Code Playgroud)

来自以下文档haml_tag:

haml_tag直接输出到缓冲区; 不应使用其返回值.如果您需要将结果作为字符串获取,请使用#capture_haml.

要解决此问题,请将Haml更改为:

- @events.each do |event|
  - display_event(event)
Run Code Online (Sandbox Code Playgroud)

(即使用-运算符代替=),或更改要使用的方法capture_haml:

def display_event()
  event = MultiJson.decode(event)
  markup_class = get_markup_class(event)
  capture_haml do
    haml_tag :li, :class => markup_class do
      haml_tag :b, "Foo"
      haml_tag :i, "Bar"
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这将使该方法返回一个字符串,然后您可以=在Haml中显示该字符串.

请注意,您需要进行其中一项更改,如果同时进行这两项更改,它们将相互取消,您将无法显示任何内容.