【问题标题】:Rails global content_forRails 全球内容_for
【发布时间】:2010-02-23 14:23:19
【问题描述】:

例子:

我有 2 个部分 _map.haml 和 _bigmap.haml。

:: _map.haml

- content_for :map do
  %script{:type => "text/javascript", :src => "http://maps.google.com/maps/api/js?sensor=true"}
  ...

:: _bigmap.haml

- content_for :bigmap do
  %script{:type => "text/javascript", :src => "http://maps.google.com/maps/api/js?sensor=true"}
  ...

在我的布局中,我将 javascripts 包含到

= yield(:map)
= yield(:bigmap)

问题 1: 这意味着谷歌图书馆将被包含两次。我该如何处理这个问题,所以库总是只加载一次? A 可能在考虑视图助手?

问题 2: 是否有可能有一个全局 content_for 字段,其中每个部分都将其内容附加到它? 谢谢。

【问题讨论】:

    标签: ruby-on-rails optimization helpers content-for


    【解决方案1】:

    您可以将inject_js 方法添加到您的应用程序助手中以在视图中使用:

    def inject_js
      @javascripts.uniq.collect{ |js|
        javascript_include_tag js
      }.join("\n")
    end
    

    然后在您的应用程序视图中:

    %html
      %head
      ...
      = inject_js
    

    在任何使用 bigmap 的视图中:

    - @javascripts << 'http://maps.google.com/maps/api/js?sensor=true'
    - @javascripts << 'bigmap'
    

    或常规地图:

    - @javascripts << 'http://maps.google.com/maps/api/js?sensor=true'
    - @javascripts << 'bigmap'
    

    因为inject_js 使用@javascripts.uniq,所以Google 库只会被加载一次。

    inject_js 代码取自 tog's tog_core。还有其他方法(inject_css 等)。

    【讨论】:

      猜你喜欢
      • 2017-12-20
      • 2011-02-27
      • 2013-08-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多