Replies: 3 comments 12 replies
-
@bissy Not sure where {%- for post in collections[tag] -%} |
Beta Was this translation helpful? Give feedback.
-
Another approach which merges the two Nunjucks filters. .eleventy.js eleventyConfig.addNunjucksFilter("related", function (collection = []) {
const { tags: requiredTags, page } = this.ctx;
return collection.filter(post => {
// Filter the specified collection, confirm it isn't the current page, and has all the required tags.
// Updated to handle potentially missing `tags` properties, per https://github.com/11ty/eleventy/discussions/2534#discussioncomment-3419991 above.
return post.url !== page.url && requiredTags?.every(tag => post.data.tags?.includes(tag));
});
}); src/_includes/layouts/post.njk{%- set relatedPosts = collections.all | related -%}
{%- if relatedPosts.length %}
<h2>Related posts</h2>
<ul>
{%- for post in relatedPosts %}
<li><a href="{{ post.url }}">{{ post.data.title }}</a></li>
{%- endfor %}
</ul>
{%- endif -%} -{%- set relatedPosts = collections.all | filterByTags(tags) | excludeFromCollection(page.url) -%}
+{%- set relatedPosts = collections.all | related -%} |
Beta Was this translation helpful? Give feedback.
-
@pdehaan This answer is dope. I've been looking for a way to filter by tags (either set by the current pages tags, or arbitrarily on the fly). I've previously used a 'contains' filter ... but it can be a little too open to what the tags actually contain.
then ....
... but if a post has the tag 'volvo xc60' it would still be included. Does the above filterByTags explicitly look for tags which only match? ...Also (maybe for another discussion thread) could the above filter be altered to filter collections via front matter fields also a bit like #637 ? |
Beta Was this translation helpful? Give feedback.
-
I would like to be able to automatically display 3 related articles on post pages based on tags.
I tried code below, but of course, not working 🥺
What should I do?
post content:
post.njk:
Beta Was this translation helpful? Give feedback.
All reactions