How to set a different background image for each page in Rails 3 site?

若如初见. 提交于 2019-12-01 18:40:19
Renra

I don't think you can do this using css. Even with scss, you must compile it to pure css before you can use it, so you can't change it on the fly. But you can omit the background image from the css and then do

<div class="container" style="background: url(<%= @my_computed_image_path %>)">
</div>

And then all you have to do is set up @my_computed_image_path in the controllers in some kind of before_filter.

You can set the background-image property directly in your html like this:

<!DOCTYPE html>
<html>
<head>
  <title>Site title</title>
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>
</head>
<body>
<div class="container" style="background-image: url(<%=@page.background_image%>); ">
<div class="content">
    <%= yield %>
</div>
<%= render 'layouts/footer' %> 
</div>
</body>
</html>

And you can set your background imagen directly from your @page variable or the way you want.

If you prefer, you can also set a different class for each page with a stylesheet like this:

.page_one{background-image: url(your_first_image.jpg)}
.page_two{background-image: url(your_second_image.jpg)}
.
.

And in your html:

<div class="container <%=dynamically set here the class from you @page%>">

You can create a my_styles.scss.erb file and set a variable like that:

$body-background-color: <%= @page.body_background_color %>

Then you could use it in your scss files.

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