Ignore Current Article

Hi,

I’ve got a recent articles section at the end of each article post, but i want to not display if it’s the current article.

At the moment this is the code im using:

<% blog.articles[0...3].each do |article| %>
<li><h5><%= link_to article.title, article %></h5>
    <div class="articlesummary">
        <%= article.summary %>
    </div>
    <span class="date"><%= article.date.strftime('%e %B %Y') %></span>
</li>
<% end %>

I’m guessing it’s something using delete_if == current_article but im not too sure!

Any help would be great!

Also whilst i’m asking a question…

As you can see in the code i’m using [0...3] to show the 3 most recent articles

I know how to use shuffle to shuffle the results, but is there a way to pick 3 random ones, not just shuffling from the first 3 entries?

To answer your second question first, try using:

blog.articles.sample(3)

For your first question, try something like this:

blog.articles.reject{|article| article == current_article}.sample(3).each...

2 Likes

@tommysundstrom that works perfectly! Thanks for your help!

Apologies for bringing back from the death this buried topic but I wanted to expand this filter a bit and instead of just having:

show 3 random articles site but do not display current article

to

show 3 random articles from X category only but don't display current article, where the “category” is defined this way in my config.rb:

locales.each_with_index do | locale, index |
  # Blog
  activate :blog do | blog |

    #[ other code ]

    blog.custom_collections = {
      category: {
        link: '{category}.html',
        template: '/category.html'
      }
    }
  end
end

You can collect articles from a given @category like this:

category_articles = blog.articles.select{ |a| a.data.category == @category }

(I assume you keep category as frontmatter category in each post.)
Generally I highly encourage you to study the https://ruby-doc.org/core-2.6.1/Array.html docs to find what you can do with arrays and collections. Change version number to you Ruby version, since there are new features in newer 2.x releases. I cannot help you with a proper handling of multiple blogs in one project, I never used it.