[英]Passing a local variable into a nested partial
我有一个页面可以大致像这样呈现一个集合:
index.html.haml
= render partial: 'cars_list', as: :this_car, collection: @cars
_cars_list.html.haml
编辑: _cars_list具有有关单个汽车的其他信息。
%h3 Look at these Cars!
%ul
%li Something about this car
%li car.description
%div
= render partial: 'calendars/calendar_stuff', locals: {car: this_car}
_calendar_stuff.html.haml
- if car.date == @date
%div
= car.date
_cars_contoller.rb
def index
@cars = Car.all
@date = params[:date] ? Date.parse(params[:date]) : Date.today
end
在日历部分中发生的事情是, this_car
始终是汽车收藏中的第一辆汽车,即,同一日期一遍又一遍地打印。
如果我将_calendar_stuff
的逻辑_calendar_stuff
cars_list
部分中,那么打印结果将按预期更改。
因此,似乎Rails每次渲染部分this_car
本地this_car
对象传递给嵌套的部分。
有人知道为什么吗?
PS如果我用
@cars.each do |car|
render 'cars_list', locals: {this_car: car}
end
我得到相同的行为。
尝试此重构,看看是否获得所需的输出:
index.html.haml
= render 'cars_list', collection: @cars, date: @date
摆脱partial
关键字,并传入@date
实例变量作为局部变量,以将逻辑封装在您的partials中。 这一点我是从Rails Best Practices获得的 。
_cars_list.html.haml
%h3 Look at these Cars!
%ul
%li Something about this car
%div
= render 'calendars/calendar_stuff', car: car, date: date
在将@cars
作为collection
传递时,此部分将引用一个称为car
的单数局部变量,然后可以将该变量与现在本地的date
变量一起传递给下一个部分。 由于正在渲染的partial与此处的位置不同(在calendars/
),因此在此处明确需要partial
关键字。
_calendar_stuff.html.haml
- if car.date == date
%div
= car.date
编辑
建议将对collection
的调用移至_cars_list.html.haml ,但这不适用于该问题。
编辑2
如果您仍想将局部变量指定为this_car
,则这是上述代码的版本,因此您将覆盖collection
将自动生成的car
局部变量。
index.html.haml
= render 'cars_list', collection: @cars, as: :this_car, date: @date
_cars_list.html.haml
%h3 Look at these Cars!
%ul
%li Something about this car
%li this_car.description
%div
= render 'calendars/calendar_stuff', this_car: this_car, date: date
_calendar_stuff.html.haml
- if this_car.date == date
%div
= this_car.date
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.