简体   繁体   English

使用Rails 3.1资产管道的JavaScript代码中的图像的URL?

[英]URL of images in JavaScript code using Rails 3.1 asset pipeline?

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文件中做同样的事情呢?

I see you are using the sass helper method. 我看到你正在使用sass helper方法。

In standard (non Sass) CSS you do something like this: 在标准(非Sass)CSS中,您可以执行以下操作:

.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

For javascript the same rules apply: 对于javascript,适用相同的规则:

file_name.js.erb

and in the file: 并在文件中:

var image_path = '<%= asset_path 'image.png' %>'

The Rails asset pipeline guide is an excellent source of information about how to use these features. Rails 资产管道指南是有关如何使用这些功能的极好信息来源。

In Rails 4, instead of using a js.erb view I recommend that you stick to the asset pipeline, and pass the URL to it with a variable instead using gon or some other technique discussed at: Ruby on Rails - Send JavaScript variable from controller to external Javascript asset file 在Rails 4中,我建议您坚持使用js.erb视图,并使用变量将URL传递给它,而不是使用gon或其他一些技术讨论: Ruby on Rails - 从控制器发送JavaScript变量到外部Javascript资产文件

With gon : 随着gon

app/views/layouts/application.html.erb: 应用程序/视图/布局/ application.html.erb:

<head>
  <meta charset="utf-8"/>
  <%= include_gon %>

app/controllers/application_controller.rb: 应用程序/控制器/ application_controller.rb:

before_filter { gon.path = asset_path 'image.png' }

app/assets/javascripts/file.js.coffee: 应用程序/资产/ Java脚本/ file.js.coffee:

alert gon.path

This method is faster because file is precompiled only once at startup, gets served by the server instead of through Rails, and on the same HTTP request as the rest of the Js. 此方法更快,因为文件在启动时仅预编译一次,由服务器而不是通过Rails提供服务,并且与其他Js在相同的HTTP请求上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM