如何通过资产管道加载css.erb文件 [英] How to load css.erb files through asset pipeline
问题描述
我希望样式表保持纯CSS,但我想使用嵌入式ruby来包含一些指向图像的动态路径:
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; }
如果将样式表从.css更改为.css.erb,则会正确解释image_path
,但是当我部署到生产环境时,资产管道不会对其进行处理.如果我对路径进行硬编码,那么在生产或开发中这都是错误的,因为它们以不同的方式加载资产.
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.
我该如何解决?
推荐答案
有效的方法如下:
可以在.css文件中添加.erb并使用ruby/rails代码.因此,我上面的问题中的摘要很好.
It's fine to add .erb to .css files and use ruby/rails code. So the snippet in my question above is fine.
您必须在/config/environments/production.rb
You have to add a line like this to your /config/environments/production.rb
config.assets.precompile = ['*.css.erb']
然后,当您运行RAILS_ENV=production bundle exec rake assets:precompile
时,将生成指纹CSS文件,并正确插入image_path.
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.
对我来说,.js文件会自动进行预编译,而无需添加任何配置选项.但是css或css.erb文件不起作用.这就是我实际上正在使用的:
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']
这篇关于如何通过资产管道加载css.erb文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!