Using Liquid, we can loop through each of the most recent blog posts, and, for each blog post, loop through each of its tags to display them. Here's how:
In the template of your main blog page, you'll see a Liquid "for loop" that iterates through each of the recent blog posts:
{% for post in page.blog.most_recent_blog_posts %}
... code to display each blog's excerpt ...
{% endfor %}
Within this loop, we need to make another loop that iterates through the tags of each post, and then to output each tag:
{% for post in page.blog.most_recent_blog_posts %}
... blog excerpt display code ...
{% if post.tags_count > 0 %}
<div class="page-tags">
<div class="padbottom">
<i class="icon-tag"></i>
<div class="page-tag-background">
{% for tag in post.tags %}
<span class="page-tag" data-id="{{ tag.id }}"><a href="{{ tag.url }}">{{ tag.name }}</a></span>
{% endfor %}
</div>
</div>
</div>
{% endif %}
{% endfor %}
The example here also includes wrappers and classes that mirror those of the default Aware theme styling for tags, but feel free to change those up to suit your own custom themes.
Showing 11 reactions
Sign in with
Can you point me to a How To to produce this very common archive feature of blogs?
Thank you in advance.
Nick D
This can be achieved with a bit of JavaScript in addition to some Liquid to grab the tags. Here’s a solution I’ve come up with:
First, on the top-level page, in order to tap into the properties of blog posts, we need a “subpage” liquid tag to access the blog via a custom theme file, which in my example I’ll call _blog_latest.html
{% subpage blog with “blog_latest” %}
In the _blog_latest.html custom theme file, we can iterate through our latest blog posts, and output the tags associated with them, with something like this:
{% for post in page.blog.most_recent_blog_posts }
{ if post.tags_count > 0 }
{ for tag in post.tags }
<span class=“page-tag”><a href=“%7B%7B%20tag.url%20%7D%7D”>{{ tag.name }}</a></span>
{ endfor }
{ endif }
{ endfor %}
What this bit of code does is it iterates through each post in our most recent blog posts, checks to see if the post contains tags, and, if it does, iterates through the list of tags and outputs the link and name of each tag.
But here we run into a problem – if multiple posts have the same tags, then the tags are duplicated, since this outputs all the tags of all the recent blog posts. I’ve solved this problem by including a script at the very bottom of _blog_latest.html to remove duplicate page tag elements:
var used = {};
$(‘.page-tag’).each(function(){
var id = $(this).attr(“data-id”);
if (used[id]) {
$(this).remove();
} else {
used[id] = true;
}
});
What I’ve done here is to make an empty array of “used” tags, and as I iterate through each tag, check in this array to see if the currently viewed tag has already been iterated across, and, if so, remove it from the DOM. Otherwise, we leave the current tag alone, add the current tag to the “used” array, and move onto the next tag.
Hope this helps :)