3

Let's first start with a code snippet to explain the issue:

= Haml::Engine.new('#bar= yield').render do
  this should show up inside div#bar, right?

Given that code and according to the haml::engine docs and more than one stackoverflow post, I would expect that the string "this should show up inside of the div, right?" would in fact end up inside the div#bar element, resulting in some html looking like this:

  <div id="bar">
    this should show up inside of the div, right?
  </div>

However, this is what I actually get:

  this should show up inside of the div, right?
  <div id="bar">
    0
  </div>

So, two questions:

  1. Why does the content from the block show up outside div#bar and
  2. What is that 0 inside the div#bar element?
Community
  • 1
  • 1
ynkr
  • 25,946
  • 4
  • 32
  • 30

2 Answers2

3

If you are trying create a helper to wrap the HAML engine, you might need to do this:

Helper:

module ApplicationHelper
  def generic_table(title, &block)
    template = File.read(File.join(Rails.root,'app','views', 'generic_table.html.haml'))
    haml_engine = Haml::Engine.new(template)
    haml_engine.render(Object.new, {:title => title}, &block)
  end
end

View:

= generic_table('Properties') do
  - capture_haml do
    Hello

I'd love to see a simpler way to do this

John Naegle
  • 8,077
  • 3
  • 38
  • 47
  • 1
    Note that if the OP had written the following (notice it is returning a string), it would also have worked as expected. Haml::Engine.new('#bar= yield').render do "this should show up inside div#bar, right?" end .In other words, pay no attention to the "do" vs "{}", that's not important – Rob May 16 '13 at 16:02
3

This is the correct behavior of code your wrote. Let see for example:

- ['1', '2' ,'3'].each do |var|
    %div= var

%div= var doesn't return as a result of block execution. It goes right in total html.

In your case:

= Haml::Engine.new('#bar= yield').render do
  this should show up inside div, right?

string this should show up inside div, right? renders as haml and goes directly into html to, and you block returns 0. That's why we see such result:

this should show up inside of the div, right?
<div id="bar">
    0
</div>

So, in your case you should do like that:

= Haml::Engine.new('#bar= yield').render { 'this should show up inside div, right?' }
alexkv
  • 5,144
  • 2
  • 21
  • 18