开发者

Rails - rendering a layout for a partial

开发者 https://www.devze.com 2023-03-28 04:59 出处:网络
Here\'s some mockup code of what I am trying to do: class ApplicationController < ActionController::Base

Here's some mockup code of what I am trying to do:

class ApplicationController < ActionController::Base
  layout "application"
end

class SomeController < ActionController::Base

  verify :method => :get, :only => [:index]
  def index
    @some_objects = Some.collect
  end

end

# Now in: views/some/index.html.erb

<% if @some_objects %>
  # use the application layout
  <%= render(:partial => 'some/objects', :locals => {:some_objects => @some_objects}) %>
<% else %>
  # use a different layout than application
  # some/sales_page --> views/some/_sales_page.html.erb
  # layouts/sales --> views/layouts/sales.html.erb
  <%= render('some/sales_page', :layout => 'layouts/sales') %>
<% end %&开发者_StackOverflowgt;

As you can see, I am trying to render a different layout than application for the partial some/sales_page. What do I have to do?

Note: my Rails version is 2.3.11.


This is very easy, the render method takes a :layout option (essentially the way you have it your example), however your layout can live in the same directory as the calling file and it uses the partial naming conventions (i.e. start with an underscore). So in the case of your example if would be something along the following lines:

#In: views/some/index.html.erb

<% if @some_objects %>
  # use the application layout
  <%= render(:partial => 'objects', :locals => {:some_objects => @some_objects}) %>
<% else %>
  <%= render(:partial => 'sales_page', :layout => 'sales_layout') %>
<% end %>

The contents of your views/some folder will then be as follows:

views/some/index.html.erb
views/some/_objects.html.erb
views/some/_sales_page.html.erb
views/some/_sales_layout.html.erb

For a little bit more info on the subject, have a look at this, this and this.


You can change layout only in controller layer.

class SomeController < ActionController::Base
  layout :choose_layout
  verify :method => :get, :only => [:index]
  def index
    @some_objects = Some.collect
  end

  private
  def choose_layout
    @some_objects = Some.collect
    @some_objects ? "application" : "different_layout"
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消