Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly rendering multiple layouts per controller in Rails

I've defined in my Users_controller:

layout "intro", only: [:new, :create]

Here's what my layout looks like: Intro.html.haml

!!! 5
%html{lang:"en"}
%head
  %title Intro
  = stylesheet_link_tag    "application", :media => "all"
  = javascript_include_tag "application"
  = csrf_meta_tags
%body{style:"margin: 0"}
  %header
    = yield
  %footer= debug(params)

When I render a page that calls for intro as the layout, it gets nested inside my application.html.haml file which is not good.

Is there some way of avoiding this undesirable nesting of layouts?

Thanks in advance!

like image 931
pruett Avatar asked Apr 15 '12 20:04

pruett


1 Answers

The problem was in my Controller. I was declaring multiple layout instances like so:

class UsersController < ApplicationController
  layout "intro", only: [:new, :create]
  layout "full_page", only: [:show]
  ...
end

Don't do this! The second declaration will take precedence and you won't get your desired affect.

Instead, if your layouts are simply action-specific, just declare it within the action like this:

def show
...
render layout: "full_page"
end

Or, if it's a bit more complex, you can use a symbol to defer the processing to a method at runtime like this:

class UsersController < ApplicationController
  layout :determine_layout
  ...

  private
    def determine_layout
      @current_user.admin? ? "admin" : "normal"
    end
end
like image 61
pruett Avatar answered Sep 19 '22 11:09

pruett