Rails 4 [removed] Having trouble with image paths

前端 未结 2 794
青春惊慌失措
青春惊慌失措 2021-01-17 11:10

I\'m trying to get the background image to change every 6 seconds and it\'s always a 404 error:

For example, the below appears in the JS console

htt         


        
2条回答
  •  终归单人心
    2021-01-17 11:49

    You can use the .erb (embedded ruby) extension to allow rails path helpers in your .js files:

    1) You save your original file (my_script.js) as my_script.js.erb with the image path helper:

    $('.holder').css({"background-image":"<%= asset_path('filenamehere.png') %>"});
    

    Also, make sure you have your asset pipeline set up correctly:

    From the Rails Asset Pipeline guide (http://guides.rubyonrails.org/asset_pipeline.html)

    2) Your javascript file (my_script.js.erb) is inside:

    app/assets/javascripts/
    lib/assets/javascripts/
    vendor/assets/javascripts/
    vendor/assets/somepackage/
    

    3) Your file is referenced in the manifest (maybe app/assets/javascripts/application.js):

    //= require my_script
    

提交回复
热议问题