渲染集合时避免多个 javascript_include_tag
Avoid multiple javascript_include_tag when rendering collections
我正在尝试以这种方式呈现一个集合
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 %>
由于 _promotion.html.erb 如果在 @promotions 中有多个促销活动,则会多次呈现,因此 javascript 标签也会被多次包含并导致问题。
我只想将 javascript 标签放在促销视图中,以便使其模块化,因此任何人都可以使用它而不必担心包含相关的 js 标签。
您可能希望在您的布局中包含该脚本标记,而不是在部分布局中。 Layouts 是包含脚本和样式表的好地方。您将只招致一次调用,响应将被缓存。最好只调用一次脚本并依赖该缓存,即使布局不必要地调用它也是如此。
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.
这就是 partials 的用途,重用相同的代码。 您不能在局部中使用(可以但不是一个好的做法)js 标记,因为它会继续在局部中为集合中的每条记录呈现内容。
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.
我认为更好的方法是进行部分内部促销,其中包含您的 js 标记并呈现部分促销
#consumer/promotions/_promotion_with_js.html.erb
<% content_for :page_js_modules do %>
<%= javascript_include_tag 'consumer/carousels' %>
<% end %>
<%= render @promotions %>
如果在其他用例中您只想包含 js 而不是促销部分,那么您始终可以将其分离出另一个部分并使用它。
我正在尝试以这种方式呈现一个集合
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 %>
由于 _promotion.html.erb 如果在 @promotions 中有多个促销活动,则会多次呈现,因此 javascript 标签也会被多次包含并导致问题。
我只想将 javascript 标签放在促销视图中,以便使其模块化,因此任何人都可以使用它而不必担心包含相关的 js 标签。
您可能希望在您的布局中包含该脚本标记,而不是在部分布局中。 Layouts 是包含脚本和样式表的好地方。您将只招致一次调用,响应将被缓存。最好只调用一次脚本并依赖该缓存,即使布局不必要地调用它也是如此。
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.
这就是 partials 的用途,重用相同的代码。 您不能在局部中使用(可以但不是一个好的做法)js 标记,因为它会继续在局部中为集合中的每条记录呈现内容。
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.
我认为更好的方法是进行部分内部促销,其中包含您的 js 标记并呈现部分促销
#consumer/promotions/_promotion_with_js.html.erb
<% content_for :page_js_modules do %>
<%= javascript_include_tag 'consumer/carousels' %>
<% end %>
<%= render @promotions %>
如果在其他用例中您只想包含 js 而不是促销部分,那么您始终可以将其分离出另一个部分并使用它。