与当地人一起渲染部分

Render partial with locals

我在我的应用程序上使用了 render with partials 一百次,但我遇到了一个问题,我不明白为什么。

我正在递归调用部分。

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

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

您也可以尝试使用简单的 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 服务器日志输出以查看正在呈现哪些视图文件。

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

  • 如果@shops.blank?