Simple related posts for Jekyll
When looking up Jekyll related posts patterns I found a few automated approaches:
-
Use the
related_posts
that’s built inThe docs for
related_posts
indicate that it should run with the--lsi
switch. I decided to try this as generic related posts. -
Show posts with the most shared tags
There are several tutorials on how to do this. I didn’t find this particularly useful for two reasons: 1. I don’t use tags, only categories, 2. a difference in one tag can be quite significant.
-
Use the
jekyll-related-posts
gem that analyzes contentThis semed an alternative to for the built-in method that can be used on Github pages. Since I don’t use Github I didn’t need this.
What I actually wanted is a way to curate specific very related posts, either on this blog or elsewhere, that would be shown with the link, title and the excerpt.
In the end, what I did was add a related
attribute to the front matter:
related:
- slug: jekyll-combining-an-external-folder-into-posts
- link: https://jekyllrb.com/
title: Jekyll • Simple, blog-aware, static sites
description: Transform your plain text into static websites and blogs
Then I added the following to the post.html
template:
{%if page.related%}
<hr>
<div class="sources">
{% for source in page.related %}
{%if source.slug%}
{%assign related = site.posts | where: 'slug', source.slug | first%}
{% if related.description != ''%}
{% assign descd = related.description %}
{% else %}
{% assign descd = related.content | strip_html | strip_newlines | truncate: 180 %}
{% endif %}
{% include link.html
title=related.title
description=descd
link=source.slug
%}
{%elsif source.link%}
{% include link.html
title=source.title
description=source.description
image=source.image
link=source.link
%}
{%endif%}
{% endfor %}
</div>
{%endif%}
link.html
is a partial similar to a Facebook or Twitter card and looks like this:
<div class="embed">
{%if include.link%}
{%if include.link contains "http"%}
<a href="{{include.link}}" target="_blank" rel="noopener">
{%else%}
<a href="/{{include.link}}">
{%endif%}
{%endif%}
{%if include.image%}
<div class="image" style="background-image: url({{include.image}});"></div>
{%endif%}
<div class="body">
<div class="content">
<div class="title">{{include.title}}</div>
{%if include.description%}
<div class="description">{{include.description}}</div>
{%endif%}
</div>
{%if include.link%}
{%if include.link contains "http"%}
<span class="link">{{include.link}}</span>
{%else%}
<span class="link">ognjen.io/{{include.link}}</span>
{%endif%}
{%endif%}
</div>
{%if include.link%}
</a>
{%endif%}
</div>