【问题标题】:rails html helperrails html 助手
【发布时间】:2010-12-16 17:18:15
【问题描述】:

我正在尝试找出最简洁的方法来生成一些 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 并且不想一遍又一遍地明确声明图像标签。

【问题讨论】:

  • 部分是可行的方法。
  • 好的,但是如何在部分内容中嵌套内容?这里是 Rails 菜鸟 =P
  • 您不能将块传递给部分。助手是更好的选择。但是我现在没有时间发布示例。

标签: ruby-on-rails haml partials


【解决方案1】:

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

我根据this blog post在此处发布此内容。
阅读全文以获得更好的解释:)

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

app/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..

希望有帮助!

【讨论】:

  • 不好。提供给 render 的块仅使用 render :update 处理。
  • 是的。 (我感到羞耻)修复它。
  • 感谢您的回答。我还没有机会尝试这个,但它是有道理的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 2011-04-19
相关资源
最近更新 更多