Acquire Asset Path from JavaScript

别等时光非礼了梦想. 提交于 2019-12-03 22:27:22

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') %>";

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

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");

For those using HAML you can do:

:javascript
   var assetPath = "#{asset_path('some_image.jpg')}";

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!