在 n 个部分后插入广告代码?

Insert ad code after n partials?

Rails 4.2

我有一个部分显示的集合 - 有没有办法在集合中的某个数字之后添加一段代码?

所以我在列表中显示了 10 个博客 post,每个 post 的格式来自部分列表。我想在每 3 posts

之后插入我的 AdSense 代码
<%= render partial: "list", collection: @posts %>

有没有办法自动做到这一点,或者我是否必须做一些事情,比如为每个 post 分配一个编号的 ID 并有 "if (id/3) % 1 == 0",并有条件地显示它?

类似于:

<% @posts.each_slice(3) do |posts| %>
   <%= render partial: "list", collection: posts %>
   <%= render partial: 'ad_sense' %>
<% end %>

可能有用

each_slice docs 进一步阅读

在部分 _list.html.erb 中,您可以检查 Rails list_iteration 提供的计数器变量。因此,您的支票将在 _list.html.erb 部分内,如:

render 'ad' if list_iteration.index % 3 == 0

您还可以使用 list_counter 助手。

读这个Rendering a collection of partials

<%= render partial: "ad", collection: @advertisements %>

This will render “advertiser/_ad.html.erb” and pass the local variable ad to the template for display. An iteration object will automatically be made available to the template with a name of the form partial_name_iteration. The iteration object has knowledge about which index the current object has in the collection and the total size of the collection. The iteration object also has two convenience methods, first? and last?. In the case of the example above, the template would be fed ad_iteration. For backwards compatibility the partial_name_counter is still present and is mapped to the iteration's index method.

你可以用循环索引做一些事情,比如

<% @posts.each_with_index do |post, index| %>
  <%= render partial: 'list', locals:{post: post} %>
  <% if index % 3 == 2 %>
     #adsense code here
  <% end %>
<%end %>