How to load css.erb files through asset pipeline

血红的双手。 提交于 2019-12-07 03:01:28

问题


I want my stylesheet to stay plain css but I want to use embedded ruby to include some dynamic paths to images:

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

If I change the stylesheet from .css to .css.erb the image_path gets interpreted correctly, but it doesn't got processed by the asset pipeline when I deploy to production. If I hard code the path in, it will be wrong either in production or development because they load assets differently.

How do I resolve this?


回答1:


Here's what works:

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

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

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

Then when you run RAILS_ENV=production bundle exec rake assets:precompile the fingerprinted CSS file will get generated and the image_path will be correctly inserted.

So this solved my problem.

For me, .js files are getting precompiled automatically without me adding any config options. But css or css.erb files weren't working. So this is what I'm actually using:

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



回答2:


You simply need to precompile your assets. It's simple:

RAILS_ENV=production bundle exec rake assets:precompile

Everything will be run through Sprockets (the asset pipeline) and dumped into public/assets. Just make sure that gets deployed to production along with the rest of the app and that should be all!



来源:https://stackoverflow.com/questions/18704453/how-to-load-css-erb-files-through-asset-pipeline

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