仅在Rails应用中的某些页面上加载Google Maps脚本

Fel*_*ger 4 javascript google-maps ruby-on-rails

我有一个Rails应用程序,它包含大约20页,只有两个我正在使用谷歌地图.

有没有更好的方法可以在某些页面上独占加载Google Maps API脚本(在head标记中):

<%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" if params[:controller] == "shops" && params[:action] == "index" %>

ADA*_*DAM 5

在您的布局文件的头部使用以下代码

<%= yield :head %>
Run Code Online (Sandbox Code Playgroud)

然后在想要包含javascript的页面的视图文件中执行此操作;

<% content_for :head do %>
  <%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

您可以将此content_for块放在视图文件中的任何位置,它将在您定义的文档的头部呈现 yield :head

更多信息请访问http://guides.rubyonrails.org/layouts_and_rendering.html#understanding-yieldhttp://guides.rubyonrails.org/layouts_and_rendering.html#using-the-content-for-method