当使用带有部分布局的rails以及使用yield关键字编码为迭代器的辅助方法时,我看到了一些奇怪的行为。我希望有人可以:
- 解释一下发生了什么以及为什么我会得到重复的渲染
- 建议一种替代方法,希望不仅仅是将我的辅助方法重新编码为返回列表的简单函数(我已经这样做了,作为临时解决方法)
因此,如果我在 Rails 3 应用程序中创建以下 3 件事,我会得到意外的输出。
[更新] 我测试了以下组合:
Rails 3.0.0 + erb (has this issue)
Rails 3.0.0 + haml (OK)
Rails 3.0.3 + erb (has this issue)
Rails 3.0.3 + haml (OK)
所以也许这是 erb 与 haml 的问题,但当我最初发现它时,它是在 haml 模板上。嗯...有人知道发生了什么事吗???
A)主模板如下所示(app/views/main/index.html.erb)
<h1>Main#index</h1>
<p>This is content from main#index before the partial template rendering
<%= render :partial => "partial" %>
<p>This is content from main#index after the partial template rendering.</p>
B)像这样的辅助方法(app/helpers/main_helper.rb)
module MainHelper
def my_iterator
yield 1
yield 2
yield 3
yield 4
end
end
C) 像这样的部分模板 (app/views/main/_partial.html.erb)
<% my_iterator do |x| %>
<p>iterator running with <%= x %></p>
<% end %>
当我在浏览器中查看结果时,我看到“iterator running with” block 总共出现了 8 次(1 2 3 4 1 2 3 4)。我已经确定它是 my_iterator 与 Rails 部分模板机制的结合的产量。如果我按如下方式编写 my_iterator ,则输出将如我所料。 (我还需要更改我的部分模板来执行 my_iterator.each)
def my_iterator
logger.debug("my_iterator called")
return [1, 2, 3, 4]
end
有没有一种方法可以对此进行编码,这样我就不会与轨道发生冲突并获得重复的渲染,但仍然可以使用yield 将辅助方法编码为迭代器?另外,有人可以准确解释重复渲染是如何发生的吗?
最佳答案
我刚刚遇到了一个非常相似的问题并设法解决了它。我相信如果重写上面的原始助手,它会按预期工作......
module MainHelper
def my_iterator(&block)
block.call(1)
block.call(2)
block.call(3)
block.call(4)
end
end
如果您调用 concat(capture(&block))
或 concat(block.call)
,Rails 3 中似乎也会出现同样的问题。在这两种情况下,只需删除 concat()
,重复的渲染就会消失。
关于ruby-on-rails-3 - 当辅助方法使用yield关键字时,Rails部分模板会重复渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4211326/