Why is this code rendering a background image on a

2019-09-06 04:16发布

问题:

I am trying to make only my index action render a stylesheet/background image, but for some reason the background image is appearing on all the other pages as well. My welcome controller is handling all of this. The layout file is called background.css.scss. Here is my welcome controller:

class WelcomeController < ApplicationController
layout :resolve_layout

def index
end

def show
end

def about
end

def testimonials
end

private

def resolve_layout
case action_name
when "index"
  "background.css.scss"

else
  "application"
end
end

end

Here is background.css.scss stylesheet:

body {
width: 100%;

background: {
  image: asset-url("sampleimage.png");
  repeat: no-repeat;
  size: 100% auto;
 }
}

index view:

background-image: url(<%= asset_path 'sampleimage.jpg' %>)

回答1:

You should use :yield in your application.html.erb layout:

In application.html.erb:

..
<head>
  <%= yield :head %>
</head>
...

Now add content_for block in index view:

<% content_for(:head) do %>
   <%= stylesheet_link_tag 'background' %>
<% end %>

Keep in mind that you should NOT have *= require_tree . in your application.css otherwise background.css.scss will got included in every view.