Acquire Asset Path from JavaScript

前端 未结 6 1004
梦如初夏
梦如初夏 2021-02-18 16:17

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

相关标签:
6条回答
  • 2021-02-18 16:29

    For those using HAML you can do:

    :javascript
       var assetPath = "#{asset_path('some_image.jpg')}";
    
    0 讨论(0)
  • 2021-02-18 16:30

    In my case, I wanted to get the stylesheet path and the hash that rails generates for cache busting made it impossible to hardcode.

    What ended up working quite well for me is to assign an ID to the main stylesheet link element in the html (layout) and then use javascript to extract the href. If you want the base asset path, perhaps create a generic element with the data you need as an attribute.

    Rendered HTML

    <link rel="stylesheet" href="mypath/main.css" type="text/css" id="main-css">
    

    JS

    $("#main-css").attr("href"); // "mypath/main.css"
    
    0 讨论(0)
  • 2021-02-18 16:35

    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') %>";
    
    0 讨论(0)
  • 2021-02-18 16:35

    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");
    
    0 讨论(0)
  • 2021-02-18 16:38

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

    0 讨论(0)
  • 2021-02-18 16:39

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

    0 讨论(0)
提交回复
热议问题