0

How do I call a method in a helper from a Haml file?

In sample.haml, I need to call the show_message method depending on some condition. Then I moved the method to the helper, but the returned value from the method is treated as just a string, not a Haml element.

This is sample.haml:

- flash.each do |msg|
  - if msg.is_a?(Array)
    - msg.each do |m|
      = show_message(m)
  - if msg.is_a?(String)
    = show_message(msg)

This is helper.rb:

  def show_message(msg)
    haml = <<-HAML
    %div{class: some_class}
      = content_tag :div, #{msg}, id: "id"
    HAML
  end

If I write the same HTML element in show_message in sample.html directly, it works properly. How can I solve this?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Makoto Taguchi
  • 129
  • 1
  • 8

1 Answers1

0

Your helper method needs to construct the full HTML via methods. Since it's not actually part of the HAML, you cannot rely on syntax like %div{class: some_class}. Something like this:

def show_message(msg)
  content_tag(:div, class: 'some_class') do
    content_tag(:div, msg, id: "id")
  end
end

See the content_tag documentation for more usage examples.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Tom Lord
  • 27,404
  • 4
  • 50
  • 77