Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How do you associate a stylesheet to a layout?

My application has a controller that uses a different layout called "special":

class SessionsController < ApplicationController
  layout "special"
  ...
end

So I've created a new layouts/special.html.erb:

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <%= stylesheet_link_tag "special" %>
  <%= csrf_meta_tags %>
</head>
<body>
 <%= yield %>
</body>
</html>

I also created a new corresponding stylesheets/special.css

The problem is when I try to access the page with the "special" layout I'm getting an exception:

Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError in Sessions#new

special.css isn't precompiled

I've already executed bundle exec rake assets:precompile, but it didn't fix the problem. What's wrong? How do you associate a stylesheet to a layout in rails?

like image 800
Maikel Avatar asked Oct 08 '22 08:10

Maikel


2 Answers

By default, Rails only precompiles your application.css and application.js files (or their .scss, .less or .coffee equivalents).

If you want an additional file to be precompiled, you must add it to the precompile array on your config/environments/production.rb, like this:

config.assets.precompile += %w( special.css )

See: http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets

like image 168
Fábio Batista Avatar answered Oct 13 '22 11:10

Fábio Batista


Just a slight modification from the accepted answer - the docs suggest adding the precompiled assets in config/initializers/assets.rb. This makes sense so that they are available in all environments without having to repeat the config set up for each. So I created that file and added the fully qualified config attribute:

Rails.application.config.assets.precompile += %w( special.css )
like image 31
Sia Avatar answered Oct 13 '22 12:10

Sia