haml_tag直接输出到Haml模板

时间:2012-05-07 20:43:55

标签: ruby-on-rails ruby haml

我的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

这是错误:

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.

模板正在调用display_event,如下所示:

 - @events.each do |event|
     = display_event(event)

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

%li.fooclass
   %b Foo
   %i Bar

1 个答案:

答案 0 :(得分:11)

错误消息中的线索:

Disregard its return value and use the - operator,
or use capture_haml to get the value as a String.

来自haml_tag的文档:

  

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

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

- @events.each do |event|
  - display_event(event)

(即使用-运算符代替=),或更改方法以使用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

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

请注意,您只需要对这些更改进行一次,如果您同时取消这两项更改,则不会显示任何内容。

相关问题