Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haml_tag outputs directly to the Haml template

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
like image 584
randombits Avatar asked May 07 '12 20:05

randombits


Video Answer


1 Answers

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.

like image 121
matt Avatar answered Sep 17 '22 14:09

matt