twigoctobercmsoctobercms-plugins

RainLab.Blog Post List: List Sub-Categories under a specific Top-Level Category


I'm working on an October CMS project which use a blog where I need to seperate blog posts in two major categories. When listing blog posts using the RainLab.Blog plugin's Post List component, I need to list categories that are sub-categories under a specific top-level category and exclude other categories.

enter image description here

In the TWIG template, I want to iterate through and list out the categories that belong to "Birds" and not "Sealife".

In the default Post List component, categories are listed like this:

{% for category in post.categories %}
    <a href="{{ category.url }}">{{ category.name }}</a>{% if not loop.last %}, {% endif %}
{% endfor %}

I would like to change this to something like this:

{% for category in post.categories %}
    {# if category is a sub-category of "Birds"... #}
        <a href="{{ category.url }}">{{ category.name }}</a>{% if not loop.last %}, {% endif %}
    {# endif #}
{% endfor %}

So I would like the post to be listed as "Shorebirds" and "Hummingbirds" but not as "Corals" as this is a category that is not a direct child of "Birds".

I came across this stack overflow question, but it avoids rendering posts that do not match the criteria all together. I still want to fetch and render posts that are in other categories, but only list the categories if they match.


Solution

  • If it's totally fine to hardcode category then you can simply compare categories parent's slug or id to hardcoded value.

    Here I am using the slug to compare parent, you can also use id it's totally up to you.

    {% for category in post.categories %}
        {% set parentCat = category.getParent().first() %}                        
        {% if parentCat.slug == 'birds' %}
        <!-- here we are ^ comparing ^  please replace value as per your need -->
            <a href="{{ category.url }}">{{ category.name }}</a>
            {% if not loop.last %}, {% endif %}
        {% endif %}
    {% endfor %}
    

    now it should only show a categories which have a parent category having given slug.

    if any doubt please comment