How to link post categories in Jekyll

I have the following code in my index.html for Jekyll. I am trying to find a way to associate the categories associated with each post with the post itself. So, if the post contains a "travel" category, I want to click on a link that says "travel" which will take me to all the items classified as such.

 <ul class="post-list" style="list-style-type: none;">
 {% for post in paginator.posts %}
    {% unless post.categories contains 'portfolio' %}
    <li>
    <h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
    <span class="post-meta">{{ post.date | date: "%c" }}</span> &nbsp;
    Filed In: 
    {% unless p.categories == empty %}
                    {% for categories in post.categories %}
                        <a href="/{{ categories | first }}">{{ categories }}</a> //problem area
                    {% endfor %}
                {% endunless %}
    &nbsp;
    {{ post.excerpt }} <a href="{{ post.url }}">Find out more...</a><br><br>    
    </li> 
    {% endunless %}
   {% endfor %}
</ul>

      

+3


source to share


1 answer


Found it out. For anyone else wondering how to do the same, set up a page categories.html

in the root directory first. This page will list all posts that match a specific category. It turns the category names into named anchor bullets as such <a href="#{{ category | first | remove:' ' }}"

, and then the previous code creates an actual named anchor div

that displays the message associated with that category. Finally, in the section or section where you want to display the list of categories, you present the last bit of code that links to the named anchor section on the page categories.html

.

First piece of code to go to categories.html

:

<h2>Posts by Category</h2>
<ul>
 {% for category in site.categories %}
<li><a href="#{{ category | first | remove:' ' }}"><strong>{{ category | first }}</strong></a></li>
{% if forloop.last %}
    {% else %}  
    {% endif %}
    {% endfor %}
</ul>

      

Second piece of code in categories.html

:

{% for category in site.categories %}
<div class="catbloc" id="{{ category | first | remove:' ' }}">
 <h2>{{ category | first }}</h2>
<ul>
{% for posts in category %}
{% for post in posts %}
{% if post.url %}
 <li>
  <a href="{{ post.url }}">
 <time>{{ post.date | date: "%B %d, %Y" }}</time> - 
{{ post.title }}
</a>
</li>
{% endif %}
{% endfor %}
{% endfor %}
</ul>
  </div>
   {% endfor %}

      



Third piece of code where you want to display your named anchored categories:

 Filed In: 
 {% unless p.categories == empty %}
 {% for categories in post.categories %}
 <a href="http://localhost:4000/category.html#{{categories}}">{{ categories }}</a>
 {% endfor %}
 {% endunless %}

      

Use the following CSS to prevent premature display of sections before clicking on them:

.catbloc:not(:target){
 display: none;
}

      

Hope this helps!

+3


source







All Articles