Avoid *.js.erb files by building all the asset_path values

后端 未结 3 1500
無奈伤痛
無奈伤痛 2021-02-04 04:51

So I want to avoid processing JavaScript files with ERB just so I can get a proper asset path to, say, an image.

Currently, this seems like the popular approach:

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 05:39

    Old question, but there is nice way to accomplish this. Just to explain the context of my solution: I need to display markers in a map, which have different possible icons based on the JS dynamic variables. Strangely, using the <%= asset_path('" + somefunction(raw_value) + "') %> was not working. Then, I've looked for the solution bellow.

    Concretely, the solution I am using has only one js.erb file which stores the values of the images, and their fingerprinted names, which can be get by a function, image_path. After that, all my other JS files can be free of the asset_path and, consequently, of the .erb

    Create a file images.js.erb in your_application/app/assets/javascripts with the following content:

    <%
        imgs = {}
        Dir.chdir("#{Rails.root}/app/assets/images/") do
            imgs = Dir["**"].inject({}) {|h,f| h.merge! f => image_path(f)}
        end
    %>
    
    window.image_path = function(name) {
        return <%= imgs.to_json %>[name];
    };
    

    Require this file in your application.js, which is normally in the same directory as above:

    //= require ...
    //= require ...
    //= require images
    //= require_tree .
    

    Then, inside the JS that you've been using <%= asset_path('image.png') %>, you will use instead image_path('image.png');

    Credits to this blog post for posting a Coffee script version from which I've based mine.

提交回复
热议问题