Skrivr – The original Dropbox powered writing app. Write, save, published!    Request an invite »

Thursday, 3 January, 2013

Use the post-feed to display all post from a category

Since we are using the TWIG template engine there is a ton of ways to make use if the greatness built into it by the SensioLabs people. One of the easiest and most useful is displaying all posts from a category a time on the main page.

To get a posts from a spacific category simply add if post.category == 'categoryname' in the for loop handling the post feed so that it looks like:

{% include 'header.html' %}
{% if post.category == 'categoryname' %}
    {{ category }}
    {% for post in post_feed %}
        {{ post.date }} 
        {{ post.headline }}
        {{ post.excerpt|raw }}
    {% endfor %}
{% end if %}
{% include 'footer.html' %}

The advanced category listing

We can even take this a step further and list each category with each post underneath. Please note that this only works on the main page.

Here is an example from some design sketches we have made:

And this is the code for it:

{% set categorys = [] %}
{% for post in post_feed %}
    {% if post.category not in categorys %}
        {% set currentCategory = post.category %}
        {% set categorys = categorys|merge([post.category]) %}
        <div class="column-wrapper">
            <div class="column category-title"><a href="{{ post.categorylink }}">{{ post.category }}</a></div>
            <div class="column posts">
            {% for post in post_feed if post.category == currentCategory %}
                <div class="article">
                    <p class="date">{{ post.date }}</p>
                    <a href="{{ post.permalink }}"><h1>{{ post.headline }}</h1></a>
                </div>
            {% endfor %}
            </div>
        </div>
    {% endif %}
{% endfor %}
More Tips and trix