3
votes

I've got the following code in my index.html for Jekyll. I'm trying to find a way to link the categories associated with each post to the actual post themselves. So, if a post contains the category "travel" I want to click on a link that says "travel" which will bring me to all posts categorized 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>
1

1 Answers

3
votes

Figured it out. For anyone else wondering how to do the same, first setup a categories.html page in your root directory. This page will list all posts that meet a specific category. It does by turning the category names into named anchor slugs as such <a href="#{{ category | first | remove:' ' }}" and then the preceding code creates the actual named anchor div which displays the post associated with that category. Finally, under the page or section where you want to display the list of categories, you present the final bit of code which links to the named anchor section in your categories.html page.

First piece of code to go into 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 to go into 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 to go where you want to display your named anchor linked 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 the sections from displaying prematurely before you click on them:

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

Hope this helps!