Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Rails make layout selection a controller concern instead of a view concern? Can I choose a layout from a view?

Maybe there's a technical/implementation reason for it, but it seems to me that "layout" is about as clearly part of the view layer as it can be, yet Rails seems to only allow specifying the layout at a controller level.

My controller shouldn't care about layouts... the templates should. Is there any way to specify which layout to use from within the .erb file?

Something like:

<%= with_layout :news_feed do %>

  <p>
    My markup in here.
  </p>

<% end %>

Or any other implementation you can think of... but the documentation only seems to refer to the layout from the controller perspective.

Maybe it wouldn't be too hard to implement a with_layout helper.

EDIT | I found exactly what I was looking for:

<% render :layout => "some_layout" do %>
  <p>
    My markup here
  </p>
<% end %>

Now provided your ActionController has:

class ApplicationController < ActionController::Base
  layout nil

Then each template can select its own layout, using this approach.

If you place a layout in app/layouts, with a name that matches the controller, that layout will be used, so you don't strictly have to specify if they are all the same. Either way, the dude how writes your templates now has full control of it, not the dude who's writing the controllers :)

like image 289
d11wtq Avatar asked May 08 '11 15:05

d11wtq


1 Answers

I did some research and I did not find any solution similar to what you're looking for.

I think that might have to do with the fact that specifying a layout other than the default can be done by naming a file your_controllers_name.html.erb under app/views/layouts. This can remove any logic from your controller if the same layout is always used for a specific controller. Maybe this is what you're looking for? If you do not have a matching controller name for a layout, then the default application.html.erb will be used.

If you need to render a different layout conditionally, then that decision does need to be made in your controller. Otherwise you would push down the decision-making logic into your view. Your view should not have to make the decision about what layout it needs because the controller is there to make decisions and set up any necessary data that a view requires.

like image 122
McStretch Avatar answered Oct 07 '22 02:10

McStretch