I'm an independent Product & Engagement Marketing helping Shopify focused businesses. In addition to my personal articles here, I also run Leader of the Pack, a blog dedicated to reviewing travel bags and accessories for people on the move. You'll also find me occasionally posting on Twitter and Instagram.
January 09, 2018
I recently added a simple “you might also like” list to the bottom of my Weekly Miscellany layout file and thought it might be worth sharing the code for other Jekyll users to use/make better.
My goal was to provide up to five links to the most recent “Weekly Miscellany” categorised posts but also ensure that if the currently viewed post was in that it wasn’t included. As with many scenarios in Liquid you have to change your way of tackling the problem, especially if you come regularly developing with server-side languages.
Here’s the code I have employed:
Here’s an explanation of the steps:
countwhich we’ll use to track the number of links we have output
forloop which will iterate over every post (the default collection in Jekyll) in the site
posthas an assigned category of
truedoes the loop continue. If
postwill be evaluated.
urlof the current
postin the loop) is the same as the page being generated by Jekyll. In order to do this, we compare the
post.urlvariable with the
post.url != page.url(i.e. if there is no match) then we run one more comparison which checks how many
postswe have already output. This utilises our
countvariable. The link will only be output if the
countis less than six. This should ensure that the list will never include a link back to itself and also ensure
assign count = count | plus: 1. This is one of those Liquid concepts which still feels a little alien to me!
ifstatements and our single
This approach will loop over every
post in the collection. This may take a while if you run a very large archive and may not be the most performant way of achieving this result. As my archive is tiny I am not concerned by this.
There’s probably a number of ways to achieve this same result but so far it seems to be working well for me.