好吧,我找到了一个解决方案:
当传递括号中的记录时,haml 使用 recordshaml_object_ref
方法来确定类和 id 前缀使用什么值。因此,我重写了渲染助手,以便它可以在渲染之前相应地调整此方法:
# config/initializers/extensions/action_view_extension.rb
#
# (For some reason that is beyond be I could override this method in
# ActionView::Helpers::RenderingHelper, so for not I patched it at class level)
#
class ActionView::Base
alias_method :original_render, :render
def render objects = [], options = {}, *args, &block
class_prefix = options[:class_prefix] || options[:namespace] || options[:as]
records = Array( objects ).select { |object| object.is_a? ActiveRecord::Base }
records.each do |record|
class_name = record.class.to_s.underscore
record.define_singleton_method :haml_object_ref do
[class_prefix, class_name].compact.join( '_' )
end
end
original_render objects, options, *args, &block
end
end
现在我可以调用render
这样的视图:
#header
%ul.lately_calling_people
%li = render @lately_calling_people[0], as: 'lately_calling'
%li = render @lately_calling_people[1], as: 'lately_calling'
%li = render @lately_calling_people[2], as: 'lately_calling'
#sidebar
%ul.interesting_people
%li= render @interesting_people[0], as: 'interesting'
%li= render @interesting_people[1], as: 'interesting'
%li= render @interesting_people[2], as: 'interesting'
#main
%div[@person]
@person.name
...
这将产生以下html:
...
<ul class="lately_calling_people"
<li><div class="lately_calling_person" id="lately_calling_person_1">...</div></li>
...
</ul>
...
<ul class="interesting_people"
<li><div class="interesting_person" id="interesting_person_1">...</div></li>
...
</ul>
...
<div class="person" id="person_1">
...
</div>
我可以保持部分简单:
# app/views/people/_person.html.haml
%div[person]
= image_tag person.image
%p.name= person.full_name
%p.location= person.location