Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different background color for different pages in rails

So I'm using an application.html.erb file which is basically the layout for every page in my website. But I want the homepage to have a white background and the rest of the pages to have a different background. The problem is, if I wrap the entire homepage file in a div, it only wraps the "yield" place and so it shows as a box with a white background within a larger box with a gray background. So how can I change the entire background of the homepage and leave the rest?

Thanks!

like image 714
Nosayr Yassin Avatar asked Jan 16 '12 16:01

Nosayr Yassin


2 Answers

Expanding on the answer provided by @muffinista: You can use an instance variable set in the controller to determine when to put the 'homepage' class on the body tag. So:

def index
  @home_page = true
  # existing code
end

and in the layout:

<body class="<%= @home_page ? 'homepage' : ''%>">
 <%= yield %>
</body>
like image 144
MrTheWalrus Avatar answered Sep 19 '22 17:09

MrTheWalrus


Consider putting a special class on the body tag (or perhaps your main wrapper) of your homepage, then do it in CSS. So you can have on your homepage:

<body class="homepage">
  <p>hi!</p>
</body>

Then on your other pages:

<body>
  <p>i am not a homepage!</p>
</body>

And in your CSS:

body {
 // some general css
}

body.homepage {
 // some css for homepage elements
 background-color: #000000;
}

UPDATE: you can use a helper like this to make life easier:

def body_class
  @body_class || ''
end

Then in your homepage views, put something like this at the top:

<% @body_class = "homepage" %>

Obviously this depends on the specifics of your app, but it works fine for me.

like image 43
muffinista Avatar answered Sep 21 '22 17:09

muffinista