我有地图小部件,我在一个页面上多次使用。
# 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
..
在此设置中,我在标题中包含了重复的脚本:
<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>
我如何只使用content_for作为我的小部件脚本一次?
答案 0 :(得分:1)
您可以使用content_for?(:head)
检查是否已定义标题内容。
修改强>
如果您想多次使用:head
,那么创建一个维护对已经包含的小部件的引用的帮助器呢?像(未经测试的代码):
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