docpad

Randomize related posts in Docpad


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()?


Solution

  • 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!