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 :)

12
задан d11wtq 8 May 2011 в 16:42
поделиться