Reputation: 356
I am trying to render a collection this way
views/consumer/home/index.html.erb
<%= render @promotions %>
consumer/promotions/_promotion.html.erb
<% content_for :page_js_modules do %>
<%= javascript_include_tag 'consumer/carousels' %>
<% end %>
Since _promotion.html.erb is rendered more than once if there are more than one promotions in @promotions, the javascript tag also gets included more than once and causing issues.
I want to put the javascript tag inside of promotion view only so as to make it modular and hence anyone can use it without worrying about including the pertaining js tags.
Upvotes: 2
Views: 618
Reputation: 9173
Since _promotion.html.erb is rendered more than once if there are more than one promotions in @promotions, the javascript tag also gets included more than once and causing issues.
This is what partials are for, to reuse same code. You can't use (you can but it won't be a good practice) a js tag inside a partial because it will keep on rendering content inside the partial for each record in collection.
I want to put the javascript tag inside of promotion view only so as to make it modular and hence anyone can use it without worrying about including the pertaining js tags.
I think a better approach would be to have a partial inside promotions which would contain your js tag and render promotion partial
#consumer/promotions/_promotion_with_js.html.erb
<% content_for :page_js_modules do %>
<%= javascript_include_tag 'consumer/carousels' %>
<% end %>
<%= render @promotions %>
if there are other use cases where you just want to include js instead of promotions partial then you can always separate out that in another partial and use it.
Upvotes: 2
Reputation: 6088
You probably want to include that script tag in your layout, not in a partial. Layouts are a good place to include scripts and stylesheets. You will incur only one call and the response will be cached. Best to call the script once only and rely on that cache, even if the layout calls it needlessly.
Upvotes: 0