【发布时间】:2017-11-13 20:45:37
【问题描述】:
问题:如何通过不同的变量进行部分(必须是通用的)循环?
我有一个标签页,我想在其中使用部分内容以避免重复我的 HTML。选项卡是“视频”和“文章”。这是完全相同的 HTML,但我想遍历 @videos 的视频和 @articles 的文章。
这个想法是让产品部分完全通用,然后以某种方式传递我想要迭代的@videos 或@articles。
部分:_product.html.slim
.col-md-5
.thumbnail
.thumb.spacer-sm
- if product.image.blank?
iframe allowfullscreen="" frameborder="0" mozallowfullscreen="" src="https://player.vimeo.com/product/#{product.vimeo_id}" webkitallowfullscreen=""
- elsif product.vimeo_id.blank?
= image_tag(product.image.url,
class: 'img img-responsive img-rounded')
.caption
.content-group-sm.media
.media-body
h6.text-semibold.no-margin
= product.name
small.text-muted
| by
= product.user.name
- unless product.price.blank?
h6.text-success.media-right.no-margin-bottom.text-semibold
| $
= product.price
= product.description
.panel-footer.panel-footer-transparent
.heading-elements
ul.list-inline.list-inline-separate.heading-text
li
= link_to 'Delete', product_path(product), method: :delete
li
= link_to 'Edit', edit_product_path(product)
呈现局部的 HTML 视图:
.page-container.spacer-minus
.page-content
.row
.col-md-4
.sidebar-default.sidebar-separate
.sidebar-content
.content-group
.panel.no-border-radius-top
ul.navigation
li.navigation-header Navigation
li.active
a data-toggle="tab" href="#videos"
i.icon-video-camera2
| Videos
li
a data-toggle="tab" href="#articles"
i.icon-graduation
| Articles
.col-md-8
.tab-content
#videos.tab-pane.fade.in.active
.row
- @videos.each do |product|
= render 'shared/product'
#articles.tab-pane.fade
.row
- @articles.each do |product|
= render 'shared/product'
我只需要我的循环来了解我想要迭代的变量。我不能在部分中包含@video 或@article,因为这会破坏具有通用部分的目的。
有了这个实现,我得到了错误:
undefined local variable or method `product' for #<#<Class:0x007fc58053ae60>:0x007fc58884ea68>
【问题讨论】:
-
这篇文章建议我可以在部分渲染之前执行一个 for 循环:stackoverflow.com/questions/1850905/…
-
尝试将本地人传递给部分
-
我该怎么做@AakashGupta?
-
= 渲染部分:“产品”,集合:@videos
-
-videos.each 做 |product| = render 'shared/product', collection: @videos 我仍然得到错误:未定义的局部变量或方法 `product' 我的部分如何知道 @video 集合被命名为 product?
标签: ruby-on-rails loops partials