无法抑制 rails 3 中嵌套块助手中的输出 [英] Can't suppress output in nested block helper in rails 3

查看:41
本文介绍了无法抑制 rails 3 中嵌套块助手中的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个有点扭曲我的面条.

This one is sort of twisting my noodle.

我有类似的东西(如果重要的话,在 rails 3 引擎中)

I have something resembling this (in a rails 3 engine if that matters)

class Builder
  def initialize
    @foos = []
  end

  def foo(&block)
    @foos << helper.capture(&block) #helper being a class that is including ActionView::Helpers
  end

  def to_html
    @foos.join "\n"
  end
end

module ApplicationHelper
  def widget
    b = Builder.new
    yield b

    b.to_html
  end
end

#in a view somewhere
<%= widget do |b| %>
  <% b.foo do %>
    static content
  <% end %>
<% end %>

一切都很好,但是嵌套的静态内容会输出两次——一次是我想要的地方,一次是调用 widget 的地方.

Everything is working out great, but that nested static content is getting output twice -- once where I want it, and once where widget was called.

据我所知,capture 应该可以解决这个确切的问题.我很确定问题源于我如何调用捕获(来自包含 ActionView::Helpers 的虚拟代理类),但问题在于 b.foo 调用在类实例上调用方法,而不是从将混合到模板中的内容的上下文中调用.

From what I have read, capture is supposed to deal with this exact problem. I am pretty sure the problem stems from how I am calling capture (from a dummy proxy class that includes ActionView::Helpers), but the problem is that b.foo call is calling a method on a class instance, not from the context of something that will be mixed into the template.

有什么办法可以解决这个问题吗?或者我是从错误的方向接近这个.我正在尝试对一些相当复杂的东西进行建模,并且对 api 感到非常满意,只是似乎无法解决这个问题.

Is there any way to get around this problem? Or am I approaching this from the wrong direction. I am trying to model something fairly involved and am really happy with the api, just can't seem to get passed this problem.

推荐答案

如果修改 helper 方法传入 self,即当前视图实例,然后使用 this 进行捕获,则可能不会出现此问题.将您对 helper 的使用替换为提供的视图实例.

If you modify the helper method to pass in self, which would be the current view instance, and then use this to capture, you might not have this issue. Substitute your use of helper for the provided view instance.

这篇关于无法抑制 rails 3 中嵌套块助手中的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆