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?
Checkout the js_assets(Javascript helper in rails projects) gem. I think it is precisely what you need.
From the documentation:
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
then in some_javascript.js
I came across the same issue in Rails 4.1 and used referencing rails assets in coffeescript for images. No additional libraries needed.
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:For those using HAML you can do: