Creating a custom tag page in Jekyll allows you to display posts associated with a specific tag, making your website more organized and user-friendly. This guide will walk you through the process of setting up a tag-specific page that dynamically filters posts based on tags.
Understanding Jekyll Tags
Jekyll uses tags to categorize posts, which helps visitors find related content easily. Tags are added in the front matter of each post like this:
tags: [tag1, tag2]
Creating a Tag Page Template
To create a custom tag page, start by making a new layout or include file. For example, create a file named tag.html in your _layouts directory. This template will display posts filtered by the current tag.
Adding Front Matter
In your tag.html layout, include the following front matter:
---
layout: default
permalink: /tag/:tag/
---
Filtering Posts by Tag
Use Liquid code to filter posts based on the tag in the URL. Here's an example snippet to include in your tag.html layout:
{% assign tag = page.url | split: '/tag/' | last | replace: '/' '' %}
{% assign tagged_posts = site.posts | where_exp: "post", "post.tags contains tag" %}
Displaying Filtered Posts
Next, iterate over the tagged_posts array to display each post:
{% for post in tagged_posts %}
<h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
<p>{{ post.excerpt }}</p>
{% endfor %}
Creating Tag Pages
To generate pages for each tag, you can create a collection or use a plugin like jekyll-tagging. Alternatively, manually create pages like tag-yourtag.html with front matter:
---
layout: tag
tag: yourtag
permalink: /tag/yourtag/
---
Conclusion
By creating a custom tag page, you enhance your Jekyll site’s navigability. Using Liquid filters, you can dynamically display posts related to specific tags, providing a better experience for your visitors and organizing content effectively.