开发者

How do I add custom javascript to my rails3 views?

What i开发者_高级运维s the best way to add JavaScript to my Rails3 views?

I would like to be able to do some processing in a controller, then craft some JavaScript based on the result and put the resulting JavaScript in a view.

For example, I would like to get a series of lat/lng points from a database and create markers on a Google Map. The map initialization and markers must be created in JavaScript, but interact with the view. (This is just one example of what I am trying to accomplish. I am not looking for recommendations of gems/plugins that do Google Maps integration).

Is there some way to render an js.erb file into the head of a particular view? What is the "rails way" of doing this sort of thing?


If you want to add the JavaScript before the page is loaded at all -- i.e. not through Ajax -- then there is no particular reason why you couldn't just create a _javascript.html.erb partial containing the script tags and then do the following in your view:

<%= render 'javascript' %>

The code in _javascript.html.erb would have access to the instance variables set in your controller, and you could write it the same way as a .js.erb file.

(Alternatively, you could use <%= yield :head %> in your layout file's <head> section and then <content_for :head do %><%= render 'javascript' %><% end %> in your views, if you want the script to be in the <head>.)

If you want to run the JavaScript on a page following an Ajax request, then just banging the code into your my_action.js.erb file and interpolating <%= @my_instance_variable.value %> as required will work -- the resulting code will be run on your page after the request finishes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜