How to display subcategories in categories menu?

Hello!
Please tell me how to display subcategories in the categories menu?

Tailor

uuid: b022a74b-15e6-4c6b-9eb9-17efc5103543
type: structure
handle: Blog\Category
name: Category
drafts: false

customMessages:
    buttonCreate: New Category

structure:
    maxDepth: 2

navigation:
    label: Categories
    parent: Blog\Post
    icon: octo-icon-list-ul
    order: 150

fields:
    description:
        label: Description

Template

<div class="sidebar-categories">
    <h3>Categories</h3>
    <ul class="bullet-list">
        {% for category in blogCategories %}
            <li class="{{ activeBlogCategory == category.slug ? 'active' }}">
                <a href="{{ 'blog/category'|page({ slug: category.slug, id: category.id }) }}">
                    {{ category.title }}
                </a>
            </li>
        {% endfor %}
    </ul>
</div>

Do one more for loop

1 Like

The best solution is to use a recursive function, you can have as many deep levels as you want without modifying the code and adding new code

In your "article/article-toc" partial - the name you want
===============================
{% macro render_toc(categories, activeSlug) %}
    {% for category in categories %}

        {% if category.is_enabled %}
            {% set hasChildren = category.children %}
            {% set isActive = category.slug == activeSlug %}
            
            <li class="{{ hasChildren ? 'collapsible' }} {{ isActive ? 'active' }}">
                <a href="{{ 'your_page'|page({ slug: category.slug }) }}" class="label">{{ category.title }}</a>
                {% if hasChildren %}
                    <ul id="tocItem{{ category.id }}" class="collapse {{ isActive ? 'show' }}">
                        {% if category.children %}
                            {{ _self.render_toc(category.children, activeSlug) }}
                        {% endif %}
                    </ul>
                {% endif %}
            </li>
        {% endif %}
    {% endfor %}

{% endmacro %}

{% import _self as categoryMenuLinks %}

{{ categoryMenuLinks.render_toc(categories, activeSlug|default(this.param.slug|default('')))|trim }}
In your template file
==========================
Set partial programmically
{% set articleTOC = partial('article/article-toc',{ categories:blogCategories })|trim %} 

Or basic way
{% partial "article/article-toc" categories=blogCategories %}
1 Like