2
votes

I am working on a Jekyll project. This is a blog with posts which have categories. I would like to succeed in having a sidebar on the right side listing the categories and the count of posts related to this category AND when clicking on the category itself, having the list of the posts related to this category.

For now, I succeeded in having the list of categories with their counts but not the display of the posts. Here is the code :

<ul class="tag-box inline">
{% assign tags_list = site.categories %}
  {% if tags_list.first[0] == null %}
    {% for tag in tags_list %}
      <a href="#{{ tag }}">{{ tag | capitalize }} <span>{{ site.tags[tag].size }}</span></a>
    {% endfor %}
  {% else %}
    {% for tag in tags_list %}
      <div><a href="#{{ tag[0] }}">{{ tag[0] | capitalize }} <span> ({{ tag[1].size }}) </span></a></div>
    {% endfor %}
  {% endif %}
{% assign tags_list = nil %}
</ul>

I was looking for some solutions on Internet and some of them were explaining that I should create a folder category and under this folder as many folder as categories I have with an index.html to display the categories. However, this is a lot of duplicated content and I don't know if it is the best way to do.

Thank you for your help!

1
Do you need to be Github pages compatible ? In other words can you use plugins ?David Jacquel

1 Answers

2
votes

As you cannot use plugins, you will have to create one page for each category. In order to avoid repeating content, you can factorize with help of layout chaining. Your category pages will use category_index.html as layout, that will itself use default.html.

Sidebar

<ul class="tag-box inline">
  {% for category in site.categories %}
    <div><a href="{{ site.baseurl }}/category/{{ category[0] }}">{{ category[0] | capitalize }} <span> ({{ category[1].size }}) </span></a></div>
  {% endfor %}
</ul>

If you want urls like category/toto/ you have to set permalink: pretty in _config.yml.

A category page : category/toto.html

---
layout: category_index
category: toto
---

That's all.

_layouts/category_index.html

---
layout: default
---
<div class="home">
  <h1 class="page-heading">Posts in category : {{ page.category }}</h1>
  <ul class="post-list">
    {% for p in site.categories[page.category] %}
      <li>
        <h2><a href="{{ site.baseurl }}{{ p.url }}">{{ p.title }}</a></h2>
      </li>
    {% endfor %}
  </ul>
</div>