Drew Johnson
Drew Johnson

Reputation: 19213

Rails: how to add a header to every page

What is the standard way to add a header and footer to every view in a Rails app?

Upvotes: 19

Views: 16879

Answers (5)

maček
maček

Reputation: 77778

If this file is found, it will be used.

app/views/layouts/application.html.erb

<!doctype html>
<html>
  <head>
    <!-- stuff -->
  </head>
  <body>
    <!-- this is where content will be rendered -->
    <%= yield %>
  </body>
</html>

Otherwise, you can call in a different one.

# app/controllers/birds_controller.rb
class BirdsController < ApplicationController

  layout :birds   # looks for app/views/layouts/birds.html.erb

  # ...
end

Upvotes: 27

sameera207
sameera207

Reputation: 16619

create a common layout 'app/views/layouts/.html.erb' as x1a4 said. And inside that you can create your header and footer

If you want you can make that as two partials and call inside the layout file. But if you have only one layout you might not need this

having header and footer in partials make sense if you have 2-3 layout types (like for normal users, administrators etc...)

and in your controllers right after the class declaration

class UsersController < ApplicationController layout 'layout name' end

cheers, sameera

Upvotes: 1

x1a4
x1a4

Reputation: 19475

put the header and footer into the application layout which can be found at app/views/layouts/application.html.erb.You may have to create this file first.

Upvotes: 9

nickname
nickname

Reputation: 1207

To add any "boilerplate" code to all pages, use a layout file. It is usually found in app/views/layouts/.

Create the page as you would with any other Rails view. In general, it is a good idea to place the <html>, body, etc tags inside of the layout to avoid repetition.

In the location where you want the content from individual views to appear, put in a <% yield %> tag. Because of Ruby's block syntax and the way Rails implements layouts, this will allow any view whose controller specifies this layout to "inherit" all of the layout and insert only the page-specific content.

To use the layout globally, name the file application.html.erb or specify the render :layout option.

Upvotes: 3

titaniumdecoy
titaniumdecoy

Reputation: 19251

You'll find your app's layout files in app/views/layouts/.

Upvotes: 1

Related Questions