【问题标题】:Render partial with locals局部渲染
【发布时间】:2015-03-18 17:14:31
【问题描述】:

我在我的应用程序上使用了数百次带有局部渲染的渲染,但我遇到了一个问题,我不明白为什么。

我正在递归调用部分。

#index.html.slim
= render partial: 'medias/special_content', locals: {shops: @shops, shop: @shop}

#medias/_special_content.html.slim
= render partial: 'medias/more_specific', locals: {shops: shops, shop: shop}

#medias/_more_specific.html.slim
- if shops.nil?
  #Some code

这是我的错误:

undefined local variable or method `shops' for #<#

<Class:0x0000000775c360>:0x007f027cff5c28>
    app/views/medias/_more_specific.html.slim:130:in
    `_app_views_medias__more_specific_html_slim___1518734296928926472_69824330512820' 
actionpack (3.2.17) lib/action_view/template.rb:145:in `block in render' 
activesupport (3.2.17) lib/active_support/notifications.rb:125:in `instrument' 
actionpack (3.2.17) lib/action_view/template.rb:143:in `render' 
actionpack (3.2.17) lib/action_view/renderer/partial_renderer.rb:265:in `render_partial' 
actionpack (3.2.17) lib/action_view/renderer/partial_renderer.rb:238:in `block in render' 
actionpack (3.2.17) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument' 
activesupport (3.2.17) lib/active_support/notifications.rb:123:in `block in instrument' 
activesupport (3.2.17) lib/active_support/notifications/instrumenter.rb:20:in `instrument' 
activesupport (3.2.17) lib/active_support/notifications.rb:123:in `instrument' 
actionpack (3.2.17) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument' 
actionpack (3.2.17) lib/action_view/renderer/partial_renderer.rb:237:in `render' 
actionpack (3.2.17) lib/action_view/renderer/renderer.rb:41:in `render_partial' 
actionpack (3.2.17) lib/action_view/renderer/renderer.rb:15:in `render' 
actionpack (3.2.17) lib/action_view/helpers/rendering_helper.rb:24:in `render' 
app/views/medias/_special_content.html.slim:20:in 
...

【问题讨论】:

  • 粘贴更多级别的堆栈跟踪

标签: ruby-on-rails ruby undefined partials


【解决方案1】:

如果它与错误源自的部分相同,那么看起来您正在从其他地方渲染more_specific 部分(即不是来自special_content 文件)并且没有通过@987654323 传递所需的变量@。因为否则,我认为这个错误是不可能的。

您也可以尝试简单的render 语法,如下所示:

render path_to_parent_partial, shops: @shops, shop: @shop # in index
render path_to_child_partial, shops: shops, shop: shop # in parent

但首先,在您的项目中搜索 'more_specific' 并查看您没有传递 shops 变量的位置。您还可以检查 Rails Server 日志输出以查看正在呈现哪些视图文件。

【讨论】:

  • 这是我检查的第一件事。如果不传递shops,则永远不会调用此部分。发生了什么是 @shops@shop 从一开始就为零?这种情况下会不会出现这个错误?
  • 没有。如果它们是 nil,那么 shops 至少应该定义为 nil
  • 我就是这么想的,为什么我用- if shops.nil?检查它
  • 我的错误.. 在网上我没有经过商店.. 真丢脸。问题解决了。感谢您的帮助。
【解决方案2】:

您可以在#medias/_more_specific.html.slim 中直接调用@shops,因为它是实例变量,因此在这里也可以使用。

  • 如果@shops.blank?

【讨论】:

  • 我不想这样做,因为这个部分是从许多其他视图中调用的,我不想每次都在我的控制器上创建一个实例变量。这就是我使用locals 的原因
猜你喜欢
  • 2015-12-16
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 2018-04-17
  • 2011-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多