6

我试图找出最干净的方法来生成一些 html 并在其中嵌套内容。使用 HAML。基本上我想做类似的事情:

= block_large
  This is some nested content

这应该产生:

<div class="block large">
  <img src="block_large_carat.gif" class="block_large_carat">
  This is some nested content
</div>

问题是我不知道如何实现这一目标。部分?帮手?我对如何嵌套我想要的任何内容感到困惑。试图保持我的 HAML DRY 并且不想一遍又一遍地明确声明图像标签。

4

1 回答 1

5

已编辑:
我以前的解决方案不起作用 :)
感谢 EmFi 指出。
这次我(甚至)测试了它,它(甚至)工作了!\o/

我根据这篇博文在这里发布这个。
阅读全文以获得更好的解释:)

app/helpers/application_helper.rb

  def block_to_partial(partial_name, options = {}, &block)
    options.merge!(:body => capture(&block))
    concat(render(:partial => partial_name, :locals => options), block.binding)
  end

应用程序/views/xxx/new.html.haml

%h2 Test!
- block_to_partial("block_large", :class_name=>"nested_content") do
  This is some nested content
OOps..

app/views/xxx/_block_large.html.haml

#block_large
  %img(src="block_large_carat.gif" class="block_large_carat")
  %div(class=class_name)
    = body

渲染:

<div id='block_large'>
  <img class='block_large_carat' src='block_large_carat.gif' />
  <div class='nested_content'>
    This is some nested content
  </div>
</div>
OOps..

希望有帮助!

于 2009-11-15T03:53:03.267 回答