0

I've installed the Related plugin for docpad and what I want to do is I want it to display five random related posts in the sidebar of every blogpost. At the moment I have it set up this way in my post.html.jade:

div
  h4 Related posts:
  each doc in getRelatedDocuments().slice(0,5)
    a(href=doc.url)= doc.title
    br

So, it displays 5 posts, but they aren't random. How do I shuffle the output of getRelatedDocuments()?

Anton Zujev
  • 147
  • 11

2 Answers2

1

Have you tried a variation on the question Getting random value from an array?

I created a function in the docpad.coffee file to implement this solution:

getRandomPosts: (howMany) ->
    items = @getCollection('posts').toJSON()
    output = []
    i = 0
    while i < howMany
        doc = items[Math.floor(Math.random() * items.length)]
        output.push(doc)
        i++

    return output

You may need an extra step in the while loop to check if the doc value is already in the output array as Math.floor etc could possibly return a value already used.

Community
  • 1
  • 1
Steve Mc
  • 3,433
  • 26
  • 35
0

Thanks to Steve Mc for pointing me in the right direction. I ended up creating this function in docpad.coffee:

shufflePosts: (items) ->
  i = items.length
  return items if i == 0
  while --i
    j = Math.floor(Math.random() * (i + 1))
    tmp = items[i]
    items[i] = items[j]
    items[j] = tmp
  return items

It is basically an implementation of the Fisher-Yates shuffling algorithm. And in my post layout I call it using:

each doc in shufflePosts(getRelatedDocuments()).slice(0,5)
  a(href=doc.url)= doc.title
  br

So now everything's great, thanks!

Anton Zujev
  • 147
  • 11
  • I'm not sold on whether this is the best way to do this. I can see problems if the collection is large or the website high volume. It would be better if this could be done using the query engine syntax (https://learn.bevry.me/queryengine/guide) - but even then you might want to cache the results. – Steve Mc May 01 '15 at 16:30
  • @SteveMc sure, but how can I use query engine to get posts with similar tags? I don't think that's possible. – Anton Zujev May 02 '15 at 13:39
  • Sorry - it's not the related posts part I was thinking of its more extracting a whole collection to shuffle/randomise and then slicing it. – Steve Mc Jun 26 '15 at 10:55