Add Post Featured Images with Liquid
I found a video online explaining how to add featured images to Jekyll posts using liquid. I followed the instructions but I needed to extend the code for especial cases. In this post I explain what I added.
My idea was to add another front matter variable for the feature image source link. This would be a simple task if we assumed that we will only get one source link per post (if always only referencing one source per image).
The featured image in my first post, a mood board, required multiple links (it is composed of multiple images). This seemed a great opportunity to practice some liquid language so here is what I did:
In every post’s front matter I assign the source of the image to a variable image_url
. If the image has only one source then the variable will be a string containing that information.
If the image refers to multiple sources then the image_url
variable will be an array containing all the sources:
In liquid, we can use the array filter “first” to check if a variable is a string or a list of elements. This way, when image_url
is an array I use a loop for displaying the links to the sources with numbers using forloop.index
.
This solution works for me for now. I am learning jekyll and liquid as I move forward, so there might be a better approach that I am not aware of - I will post a better solution in the future if I find one.