How to Setup and Add Jekyll Categories [Simple Guide]
You can add categories to any post or page on your Jekyll. Then you can display:
- a list of all category names on any page you want
- a list of all post titles organized by their categories
- a list of all post titles and post excerpts
Show All Category Names
To display all the categories add the following code in your prefered categories page.
---
layout: page
---
<div>
{% for category in site.categories %}
<h3>{{ category[0] }}</h3>
{% endfor %}
</div>
Results
Show Posts For All Categories
To display the post titles under each category as a list, add:
---
layout: page
---
<div>
{% for category in site.categories %}
<h3>{{ category[0] }}</h3>
<ul>
{% for post in category[1] %}
<li>
<a href="{{ post.url }}">{{ post.title }}</a>
</li>
{% endfor %}
</ul>
{% endfor %}
</div>
Results
Add Excerpts For All Posts
Now to show an excerpt of the posts, put the following code:
---
layout: page
---
<div>
{% for category in site.categories %}
<h3>{{ category[0] }}</h3>
{% for post in category[1] %}
<article>
<h2>
<a href="{{ post.url }}">{{ post.title }}</a>
</h2>
</article>
{{ post.content | markdownify | strip_html | truncatewords: 30 }}
{% endfor %}
{% endfor %}
</div>
Results
Show One Category With All Its Posts
If you would like to create a list of posts for one category, you need to:
Create a new file for example home.md
. Add your prefered page layout, title and permalink.
---
layout: page
---
If your category is HTML, then you will get posts in the HTML category with site.categories.Home
.
<div class="posts">
{% for post in site.categories.Home %}
<article class="post">
<h1 class="post-title">
<a href="{{ post.url | relative_url }}">
{{ post.title }}
</a>
</h1>
{{ post.content | markdownify | strip_html | truncatewords: 30 }}
</article>
{% endfor %}
</div>
Your html.md
file should now be:
---
title: HTML Articles
layout: default
permalink: /html/
---
<div class="posts">
{% for post in site.categories.HTML %}
<article class="post">
<h2>
<a href="{{ post.url }}">
{{ post.title }}
</a>
</h2>
<span class="post-date">{{ post.date | date_to_string }}</span>
{{ post.content | markdownify | strip_html | truncatewords: 50 }}
<a href="{{ post.url }}">
<strong>Read more</strong>
</a>
<hr>
</article>
{% endfor %}
</div>
Results