【问题标题】:Insert ad code after n partials?在 n 个部分后插入广告代码?
【发布时间】:2015-06-27 01:15:05
【问题描述】:

Rails 4.2

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

所以我有 10 篇博客文章显示在一个列表中,每篇文章的格式都来自部分列表。我想在每 3 个帖子后插入我的 AdSense 代码

<%= render partial: "list", collection: @posts %>

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 partials


    【解决方案1】:

    在部分_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 %>
    

    这将呈现 “advertiser/_ad.html.erb” 并将局部变量 ad 传递给模板进行显示。 一个迭代对象将自动提供给模板,其名称形式为 partial_name_iteration。迭代对象知道当前对象在集合中的索引以及集合的总大小。迭代对象也有两个方便的方法,first?last?。在上面的例子中,模板是fed ad_iteration。为了向后兼容,partial_name_counter 仍然存在,并映射到迭代的 index 方法。

    【讨论】:

      【解决方案2】:

      类似:

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

      可能有用

      each_slice docs进一步阅读

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多