我有一个包含大约 20 个页面的 Rails 应用程序,其中只有两个页面我使用的是 Google map 。
有没有比这个(在 head 标签中)更好的方式在某些页面上专门加载 Google Maps API 脚本:
<%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" if params[:controller] == "shops" && params[:action] == "index" %>
最佳答案
在布局文件的头部使用以下代码
<%= yield :head %>
然后在要包含 javascript 的页面的 View 文件中执行此操作;
<% content_for :head do %>
<%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" %>
<% end %>
您可以将此 content_for block 放在 View 文件中的任何位置,它将呈现在您定义了 yield :head
更多信息在这里 http://guides.rubyonrails.org/layouts_and_rendering.html#understanding-yield在这里 http://guides.rubyonrails.org/layouts_and_rendering.html#using-the-content-for-method
关于javascript - 仅在 Rails 应用程序的某些页面上加载 Google map 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18403591/