Chris
Chris

Reputation: 6246

Rails specify layout for static pages

My application has some static content:

root :to => 'pages#home'
match '/about',   :to => 'pages#about'
match '/contact', :to => 'pages#contact'
match '/help',    :to => 'pages#help'

I want these pages to share a layout rather than duplicate the header / footer in each file.

The only documentation around layouts I have found seems to indicate that I should specify my layouts at the controller level, is that correct?

If so, how should give my static pages layouts? The only workaround I see is to create a bunch of empty controllers for each page, for the sole purpose of specifying a common layout file, but that smells like overkill.

Am I missing a trick?

Thanks for any help

Upvotes: 1

Views: 4983

Answers (3)

Lukas
Lukas

Reputation: 10360

If you want to set one layout (for example no layout) for all your static pages create a file config/initializers/high_voltage.rb and put

HighVoltage.configure do |config|
  config.layout = 'your_layout' # false for no layout
end

from https://github.com/thoughtbot/high_voltage#override

Upvotes: 2

Rob Davis
Rob Davis

Reputation: 15772

Yes, set the layout at the controller level. You could create a controller for this group of pages like this:

class AboutController < ApplicationController
    layout "about"

    def about
    end

    def contact
    end

    def help
    end
end

I tend to use the name "AboutController" for this sort of thing, to avoid confusion with truly static files that don't pass through a controller at all. But you could name it whatever you like.

Point your routes at it (e.g. about#contact). Then create the layout in app/views/layouts/about.html.erb

If you ever need to change the layout for a particular action, you can use the render method's :layout option:

def something_special
    render :layout => "other"
end

You can also pass false if you don't want a layout at all, like for robots.txt.

Upvotes: 4

Seamus Abshere
Seamus Abshere

Reputation: 8516

Per GoodEnough's comment, you could use a gem like high_voltage

It defaults to using the "application" layout, but you can change this in one of two ways:

One layout globally

HighVoltage.layout = 'foobar' - if all of your static pages have the same layout

Varying layouts

Create a PagesController of your own:

class PagesController < HighVoltage::PagesController
  layout 'foobar'

See the Override section of the docs for the full scoop.

Upvotes: 0

Related Questions