Different background color for different pages in rails

不羁岁月 提交于 2019-12-02 19:49:26

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 %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!