Supritha
Supritha

Reputation: 53

Rails - How do I use application.html.erb in my custom layout?

I have a Controller called "Pages" with around 5 pages (views) for which I have rendered a layout called "page.html.erb". So my "Pages" Controller has:

class PagesController < ApplicationController
layout 'page' 

I want my "page.html.erb" layout to use "application.html.erb" by default. How do I do make my custom layout "page.html.erb" to automatically have "application.html.erb" inherited/rendered in it?

Upvotes: 5

Views: 4046

Answers (3)

Promise Preston
Promise Preston

Reputation: 28800

I had a similar challenge like you, but for mine I wanted my home page to have a slightly different header from the other pages.

Here's how I got it working:

All I had to do was to create 2 header partials in the app/views/shared directory:

_home_header.html.erb
_other_header.html.erb

Then I referenced it this way in the app/views/layouts/application.html.erb file:

<%= render partial: '/shared/home_header' if params[:controller] == 'homes' %>
<%= render partial: '/shared/other_header' if params[:controller] != 'homes' %>

It can also be referenced this way using an explicit if conditional:

<% if params[:controller] == 'homes' %>
  <%= render partial: '/shared/home_header' %>
<% elsif params[:controller] != 'homes' %>
  <%= render partial: '/shared/other_header' %>
<% else %>
<% end %> 

Thank you steve klein for your comment that gave me an insight into this.

That's all.

I hope this helps

Upvotes: 1

Omar Ali
Omar Ali

Reputation: 8627

I usually split my layout into smaller partials (header, footer, HTML HEAD, etc). This way I can use multiple layouts by mixing different partials together.

Upvotes: 3

steve klein
steve klein

Reputation: 2629

If you don't specify a layout in your controller, Rails will render your application layout by default. If you follow this convention, you can use application.html.erb for your overall site page structure (also a good place to include stylesheets and javascript). You can then use = yield in your layout to specify where your controller views should be rendered.

Controller actions by default will render their corresponding views. For example, if you have an action foo in controller bars_controller.rb, Rails will render /app/views/bars/foo.html.erb unless you redirect or specify a different view to render in the action. In fact, if all you want to do in action foo is render the page, you don't even need to define the action in your controller!

Convention over configuration my friend.

Upvotes: 4

Related Questions