使用 Rails 3.1 资产管道的 JavaScript 代码中的图像 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7381041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
URL of images in JavaScript code using Rails 3.1 asset pipeline?
提问by pupeno
In CSS files, you can get the proper name of an image asset (with the fingerprint) by using:
在 CSS 文件中,您可以使用以下方法获取图像资产的正确名称(带有指纹):
background-image: url(image-url("rails.png"))
but how do you do the same from a JavaScript file?
但是你如何从 JavaScript 文件中做同样的事情呢?
回答by Richard Hulse
I see you are using the sass helper method.
我看到您正在使用 sass 助手方法。
In standard (non Sass) CSS you do something like this:
在标准(非 Sass)CSS 中,您可以执行以下操作:
.class { background-image: url(<%= asset_path 'image.png' %>) }
.class { background-image: url(<%= asset_path 'image.png' %>) }
The CSS file will need to have erb added to the extensions:
CSS 文件需要将 erb 添加到扩展名中:
file_name.css.erb
file_name.css.erb
For javascript the same rules apply:
对于 javascript,同样的规则适用:
file_name.js.erb
file_name.js.erb
and in the file:
并在文件中:
var image_path = '<%= asset_path 'image.png' %>'
var image_path = '<%= asset_path 'image.png' %>'
The Rails asset pipeline guideis an excellent source of information about how to use these features.
Rails资产管道指南是有关如何使用这些功能的极好信息来源。