An easy way to support tags in a jekyll blog

Viewed 14987

I am using the standard jekyll installation to maintain a blog, everything is going fine. Except I would really like to tag my posts.

I can tag a post using the YAML front matter, but how do I generate pages for each tag that can will list all posts for a tag?

7 Answers

I do these with CSS. First lists an element and use the tag name as its id.

<span id="{{ site.posts | map: 'tags' | uniq | join: '"></span><span id="' }}"></span>

And then lists all the post and use its tags as a value for the "tags" custom attribute.

{% for post in site.posts %}
    <article class="post" tags="{% for tag in post.tags %}{{tag}}{% if forloop.last == false %}{{" "}}{% endif %}{% endfor %}">
        <h3><a href="{{post.url}}">{{post.title}}</a></h3>
    </article>
{% endfor %}

And then in CSS, hide all the posts by default, and only show posts with tags matches the url id/ hash

.post {
    display: none;
}
{% for tag in site.tags %}#{{tag[0]}}:target ~ [tags~={{tag[0]}}]{% if forloop.last == false %}, {% endif %}{% endfor %} {
    display: block;
}
/*
The compiled version will look like this
#tagname:target ~ [tags~="tagname"], #tagname2:target ~ [tags~="tagname2"] {
   display: block;
}
*/

I made an article about this here.

Related