am-rails
am-rails

Reputation: 1473

How do I use 2 Layouts for Pages in Rails?

All the pages on my site use the application layout. I want my static pages to also use the Static Pages layout. How do I use both layouts together?

Application Layout:

<html>
<head></head>
<body>
<%= yield %>

</body>
</html>

Static Pages Layout:

<div class="static">
</div>

Static page:

<p>Hello</p>

I want the page to result in:

 <html>
   <head></head>
   <body>

    <div class="static">
    <p>Hello</p>
    </div>

   </body>
 </html>

Upvotes: 0

Views: 160

Answers (3)

sites
sites

Reputation: 21795

From http://guides.rubyonrails.org/layouts_and_rendering.html#using-nested-layouts

Inside your second layout, static pages layout:

Static layout

<%= render :template => 'layouts/application' %>

Application layout

<%= yield %>

Controller where you want to use static layout

class AController
  layout 'static_layout'

static_layout should be in views/layouts.

I suppose you could use layout convention too:

class StaticController

And a file app/views/layouts/static.html.erb

Or select layout in render call:

render 'something', layout: 'static'

Upvotes: 2

Salil
Salil

Reputation: 47482

You need to understand the used of the yield

application.html.erb

<html>
  <head></head>
  <body>
    <% if @static %>
      <div class="static">
        <%= yield :static %>
      </div>
    <% end %>
    <%= yield %>
  </body>
</html>

static_page.html.erb

<% content_for :static do %>
  <p>Hello</p>
<% end %>

Only thin you need to take care now in static page controller action set a @static to true

Upvotes: 1

Amar
Amar

Reputation: 6942

Hi In controller use layout

class StaticPagesController < .....

 # you can apply only,execpt if you want 
 layout 'static'

  def home

  end
end

Upvotes: 0

Related Questions