开发者

HAML block returning `0` on yield?

开发者 https://www.devze.com 2023-01-14 05:15 出处:网络
I just upgraded to Rails3, Ruby 1.9.2 and the latest HAML gem. This code used to work: = allowed? do = link_to(\'New\', new_video_path)

I just upgraded to Rails3, Ruby 1.9.2 and the latest HAML gem. This code used to work:


  = allowed? do
    = link_to('New', new_video_path)

Now allowed? yields 0.

It works if I do:


  = allowed?开发者_运维问答{ link_to('New', new_video_path) }

What gives?


The cleanest way to do this yield concept to allow whatever content you'd like to be properly captured is:

= allowed? do
  - capture_haml do
    = link_to('New', new_video_path)

In your case, though, why not just write another helper method?

def allowed_link_to(*args, &block)
  opts = args.extract_options!
  if allowed? args.last
    link_to args.push(opts), &block
  else
    ''
  end
end

And use it like this:

= allowed_link_to('New', new_video_path)


Why are you echoing the output of that in the first place? You should be doing:

- allowed? do
  = link_to('New', new_video_path)

In general, you never want to use the output operator (=) with a block. Stuff outputted in blocks doesn't get returned to the block; it's concat'd directly into the buffer. Using a block like that is likely to produce errors with content out of order.


This took me a while to find, but this is how you do it:

def wrap_in_div(&block)
  "<div>#{capture_haml(&block)}</div>"
end

The problem is that haml outputs everything to its own special buffer before sending it on to rack or wherever. So you have to let haml call the block first and buffer it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号