How to load css.erb files through an asset pipeline

I want my stylesheet to remain plain css, but I want to use the built-in ruby ​​to include some dynamic image paths:

.home {background: #FFF url(<%= image_path 'hippopotamus.jpg' %>) no-repeat; } 

If I change the stylesheet from .css to .css.erb, the image_path will be interpreted correctly, but it is not processed by the asset pipeline when deployed to production. If I hardcode the path, it will be wrong either in production or in development, because they load assets in different ways.

How to resolve this?

+6
source share
2 answers

Here's what works:

It's great to add .erb files to .css and use the ruby ​​/ rails code. So the snippet in my question above is good.

You should add a line like this to /config/environments/production.rb

 config.assets.precompile = ['*.css.erb'] 

Then, when you run RAILS_ENV=production bundle exec rake assets:precompile , a fingerprint file will be created and the image path will be inserted correctly.

So that solved my problem.

For me .js files are automatically compiled without adding any configuration parameters. But css or css.erb files did not work. So this is what I actually use:

 config.assets.precompile = ['*.js', '*.css', '*.css.erb'] 
+5
source

You just need to pre-assemble your assets. It's simple:

 RAILS_ENV=production bundle exec rake assets:precompile 

Everything will be done through Sprockets (asset pipeline) and dumped into public / assets. Just make sure it is deployed for production along with the rest of the application, and that should be all!

+2
source

Source: https://habr.com/ru/post/953508/


All Articles