Rails global content_for

Example:

I have 2 partial _map.haml and _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"}
  ...

In my layout, I include javascripts in

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

QUESTION 1: This means that the Google library will be included twice. How can I handle this, so the library always loads only once? And I thought about the look of hever, maybe?

QUESTION 2: Is it possible to have a global content_for field in which each part adds it to it? thank.

+3
source share
1 answer

You can add a method inject_jsto your application helper for use in views:

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

Then in the view of your application:

%html
  %head
  ...
  = inject_js

and in any view using 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 tog_core. (inject_css ..).

+4

Source: https://habr.com/ru/post/1734074/


All Articles