Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acquire Asset Path from JavaScript

Tags:

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?

like image 837
senfo Avatar asked Nov 15 '12 15:11

senfo


2 Answers

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') %>"; 
like image 89
BaronVonBraun Avatar answered Sep 28 '22 10:09

BaronVonBraun


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')

like image 25
Pikachu Avatar answered Sep 28 '22 10:09

Pikachu