ole
ole

Reputation: 5233

Rails: content_for once

I have map widget, which I use multiple times at one page.

# app/cells/map/_show.html.slim
..
= content_for :head
  script src="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.js"


# app/views/some/show.html.slim
..
= render_cell :map, :show, object: object1
..
= render_cell :map, :show, object: object2


# app/views/layouts/application.html.slim
doctype html
html 
  head
    ..
    = yield :head
  body
    ..
    = yield
    ..

In this setup, I have duplicated included script in the header:

<head>
  ...
  <script src="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.js"></script>
  <script src="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.js"></script>
</head>

How I can use content_for for my widget script only once?

Upvotes: 2

Views: 670

Answers (1)

Jef
Jef

Reputation: 5474

You may use content_for?(:head) to check whether header content has already been defined.

EDIT

If you want to use :head multiple times, what about creating an helper that maintains references to widgets already included ? Something like (untested code):

module ContentHelper
    def content_for_head_once( widget_id, &block )
        @included_widgets ||= []
        unless @included_widgets.include?(widget_id)
            @included_widgets << widget_id
            content_for(:head, &block)
        end
    end
end

Upvotes: 1

Related Questions