Search code examples
javascriptruby-on-railsrubyjplayer

passing variable to js.erb file


This is the code for the jplayer:

songs/show.html.erb

<% content_for :mp3script do %>
    <script type="text/javascript">
    //<![CDATA[
    $(document).ready(function(){

      $("#jquery_jplayer_1").jPlayer({
        ready: function () {
          $(this).jPlayer("setMedia", {
            mp3: "<%= @song.mp3.url %>"
          }).jPlayer("play");
        },
      });
    });
    //]]>
    </script>
<% end %>

I have this on the head of application.html.erb:

 <%= yield :mp3script %>

Everything works fine, but it's a bit ugly to put the JavaScript inside html directly, so I want to put it in a .js.erb file.

When I put it in mp3script.js.erb it give this error:

undefined method `mp3' for nil:NilClass

If I succeed in putting the javascript in a .js.erb is the javascript application.js going to be re-compiled every time the mp3 link change in production? I think this is bad, right?


Solution

  • You can't push data from controllers into the asset pipeline, the asset pipeline has no access to your controller's instance variables or even the current request object, as they will not exist when the assets are precompiled.

    Your current approach is correct.

    is the javascript application.js going to be re-compiled every time the mp3 link change in production?

    No, that isn't how the asset pipeline works, and it's precisely the reason you can't move your dynamically generated JavaScript into a .js.erb file.