Rails 3和部分布局

时间:2012-02-26 18:37:26

标签: ruby-on-rails ruby-on-rails-3 partials

我正在尝试为每个对象呈现相同格式的不同对象的集合。我想保持干燥,所以我想使用部分和partial layouts

编辑 - 简要说明:我需要的不是在所有发布页面上显示常用项目,而是在每个项目上显示常用属性/字段。这就是我需要部分布局的原因,例如部分的布局,而不是页面的布局。

我有一系列不同的对象:

@publications = Publications.all
# Publication is the parent class
# @publications = [ImagePost, VideoPost, TextPost, ...]

我想在列表中呈现所有出版物。每个出版物都有一些共同的属性:作者,日期,......我想将这些属性放在部分布局中。

所以在我看来,为了渲染集合,我做了:

<%= render :partial => 'publications', :locals => {:publications => @publications} %>

在第一级部分views/publications/_publications.html.erb中,我在项目上循环并尝试使用公共部分布局渲染每个项目的部分:

<ul class='publications_list'>
  <% publications.each do |p| %>
    <%= render p, :layout => 'publications/publication_layout' %>
  <% end %>
</ul>

部分布局views/publications/_publication_layout.html.erb

<li>
  <h2><%= link_to publication.title, publication %></h2>
  ... Other common properties that I want to display on each item, independently of its type ...
  <p><%= yield %></p>
</li>

最后,对于每种对象类型,我都有一个部分(例如image_posts/_image_post.html.erb等),其中包含要正确显示的代码。

我的问题:我无法在公共部分布局publication_layout中呈现每个出版物。 rails简单地忽略了这种布局。每个项目都已正确呈现,但没有包含公共属性和<li>标记的布局。

有关为何忽略部分布局的任何建议?

3 个答案:

答案 0 :(得分:2)

答案和解决方法

感谢@MarkGuk在doc:

中发现了这一行
  

另请注意,明确指定:传递时需要部分   其他选项如:layout。

因此,在每个项目的同一部分内简单地呈现多态集合是不可能的。

解决方法1:我首先尝试为每个项目计算部分路径,为方便起见将其存储在模型中,然后使用良好的布局渲染好部分中的每个项目。但是我意识到这个方法,我不能在布局中引用对象publication ...

<ul class='publications_list'>
  <% publications.each do |p| %>
    <% # p.partial = p.class.to_s.underscore.pluralize +'/'+ p.class.to_s.underscore %>
    <%= render :partial => p.partial, :object => p, :as => :publication, :layout => 'publications/publication_layout' %>
  <% end %>
</ul>

解决方法2: 最后我使用了嵌套的部分。

<ul class='publications_list'>
  <% publications.each do |p| %>
    <%= render :partial => 'publications/publication_layout', :object => p, :as => :publication %>
  <% end %>
</ul>

并在布局中用yield替换render publication

答案 1 :(得分:0)

我想知道nested layout是否可以在这里为您提供更好的服务。指南应该指出你正确的方向,我发现它很容易上班,但作为一个开始:

views/layouts/application.html.erb中,将yield更改为:

<%= content_for?(:publication_content) ? yield(:publication_content) : yield %>

消除部分views/publications/_publication.html.erb,而是创建嵌套布局views/layouts/publication.html.erb

<% content_for :content do %>
    # Put common items here
    <%= content_for?(:content) ? yield(:content) : yield %> # this is for specifics
<% end %>

<%= render :template => 'layouts/application' %>

然后,可以在视图中进一步嵌套特定布局或使用其他标签指定,具体取决于您的其他设置。

答案 2 :(得分:0)

相关问题