33

I'm coming from PHP development and I'm trying to learn Ruby on Rails. I'd like to know what is the best practice for inserting headers and footers? Typically in PHP i'd just do include('header.php'); and then include('footer.php');

Now I'm trying to learn Ruby on Rails and trying to understand how or where I should put these header/footer files?

I created a new application

rails new new_app

Then I generated a new controller

rails generate controller SignUp

This created some files and folders. I've developed some HTML inside the new new_app/views/sign_up folder, but I'd like to include header and footer to this page and for future pages. Where should I have these files? In the same folder? or under the default folder in new_app/views/layouts? Also, how do I even include files once I created them?

I'm new to ruby on rails development and I'd like to gain some knowledge from experts! Thanks!

hellomello
  • 8,219
  • 39
  • 151
  • 297

2 Answers2

73

In the new_app/views/layouts there will be a file called application.html.erb. Open that file and put your header content above where it is written <%= yield> and footer content below <%=yield>.

I usually make a parital in layouts file called _header.html.erb and _footer.html.erb and do something like this :-

<%= render "layouts/header" %>
<%=yield %>
<%= render "layouts/footer" %>
simeg
  • 1,889
  • 2
  • 26
  • 34
Dev R
  • 1,892
  • 1
  • 25
  • 38
  • I added the file `_header.html.erb` and `_footer.html.erb` and included the code you listed in my `application.html.erb` but I'm getting an error `ActionView::MissingTemplate`... also, how come the first line in your code there's a `%` after `"header"` and the others don't have `%`? – hellomello Mar 10 '13 at 02:48
  • edited my answer, you have to give the location while rendering, in this case you have to say that your header and footer partials are in layouts folder. The edited answer should work – Dev R Mar 11 '13 at 05:42
2

You could create a partial for header and footer, and include them using render in the layout file, if you have dynamic content. Else you could just edit your layout file to have the header and footer.

Your scaffold generated views for SignUp, will all use the layout file to render the final HTML, so everything in the app/views/layouts/application.html.erb file will get included in the output (assuming that you are using this file as the layout file for your view).

Srikanth Venugopalan
  • 9,011
  • 3
  • 36
  • 76