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!
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>
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.
Just to add to the accepted answer, if you need to set different backgrounds for multiple pages, it would make sense and add readability to move the code for finding an appropriate background into a partial:
<body class= <%=render partial: "layouts/background" %> >
_background.html.erb:
<%- if @main_page_background OR @stylish_background %>
"main_page_background"
<%- elsif @dark_background %>
"dark_page_background"
<%- else %>
""
<% end %>
来源:https://stackoverflow.com/questions/8882828/different-background-color-for-different-pages-in-rails