haml_tag outputs directly to the Haml template

haml, ruby, ruby-on-rails

Solution

The clue’s in the error message:

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

From the docs for `haml_tag`:

`haml_tag` outputs directly to the buffer; its return value should not be used. If you need to get the results as a string, use `#capture_haml`.

To fix it, either change your Haml to:

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

(i.e. use the `-` operator instead of `=`), or change the method to use `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

This will make the method return a string, which you can then display with `=` in your Haml.

Note you need to make only one of these changes, if you make both they will cancel each other out and you’ll get nothing displayed.

Problem

What am I doing wrong with this helper for my HAML template? ``` 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 ``` This is the error: ``` 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. ``` The template is calling display_event like this: ``` - @events.each do |event| = display_event(event) ``` If I was using regular markup it would expand to the following ``` %li.fooclass %b Foo %i Bar ```

Original source