Acquire Asset Path from JavaScript

2019-04-03 18:16发布

I need to display images on an HTML5 canvas that are in the Rails asset pipeline, but I need to know the path for the asset from JavaScript. I'm using js-routes for other parts of the application, but it doesn't appear to provide a way to get the path to something in the asset pipeline.

What's the correct way to obtain the path to a Rails asset (e.g., an image) from JavaScript?

5条回答
Summer. ? 凉城
2楼-- · 2019-04-03 19:03

Checkout the js_assets(Javascript helper in rails projects) gem. I think it is precisely what you need.

From the documentation:

Get the path to the template app/assets/javascripts/rubrics/views/index.html in javascript: var path = asset_path('rubrics/views/index.html')

查看更多
我想做一个坏孩纸
3楼-- · 2019-04-03 19:05

Why not add a data attribute for the path inside an element in your .erb file and then retrieve that with JQuery?

inside some_template.html.erb

<%= content_tag(:div, "", id: 'some-id', data:{path_to_asset: asset_path("some_image.png")}) %>

then in some_javascript.js

var assetPath = $("#some-id").data("pathToAsset");
查看更多
祖国的老花朵
4楼-- · 2019-04-03 19:06

I came across the same issue in Rails 4.1 and used referencing rails assets in coffeescript for images. No additional libraries needed.

查看更多
Luminary・发光体
5楼-- · 2019-04-03 19:09

In the Rails Asset Pipeline guide, they give an example of coding assets in your stylesheets by preprocessing the stylesheets with ERB. You can use the same technique with JavaScript, assuming you tack an .erb to the end of the filename:

var someAssetPath = "<%= asset_path('some_image.png') %>";
查看更多
迷人小祖宗
6楼-- · 2019-04-03 19:19

For those using HAML you can do:

:javascript
   var assetPath = "#{asset_path('some_image.jpg')}";
查看更多
登录 后发表回答