Rails html 帮助器

发布于 2024-08-11 01:25:35 字数 396 浏览 5 评论 0原文

我正在尝试找出生成一些 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 干燥,并且不想一遍又一遍地显式声明图像标签。

I'm trying to figure out the cleanest way to generate a bit of html AND nest content inside it. Using HAML. Basically I want to do something like:

= block_large
  This is some nested content

And that should generate:

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

The problem is I don't know how to go about achieving this. Partials? Helper? I'm getting hung up on how I would nest whatever content I want. Trying to keep my HAML DRY and don't want to have to explicitly declare the image tag over and over again.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没︽人懂的悲伤 2024-08-18 01:25:35

编辑:
我之前的解决方案不起作用:)
感谢 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

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

希望有帮助!

Edited:
My previous solution didn't work :)
Thanks EmFi for pointing it out.
This time I (even) tested it and it (even) worked! \o/

I'm posting this here based on this blog post.
Read the full post for a much better explanation :)

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

Renders:

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

Hope that helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文