am-impact / amnav

Navigation plugin for Craft
168 stars 19 forks source link

Add Categories or Category Group #11

Closed engram-design closed 9 years ago

engram-design commented 9 years ago

Would be great to be able to select either existing individual categories or category groups to add to menus, just like entries work. Aware that you can add these in manually, but from a maintenance point of view, it'd be great that navigation items update when category url's change.

An even greater feature would be to select a top-level menu item and have its children auto-populate with a selected category.

alexbrindalsl commented 9 years ago

I second this request - i've made a not too messy work around.

In your menu template you can use something like this....

{% set nav = craft.amNav.getNavRaw("menu") %}

{# single level category listing for menus, just use '%%category%%category-id' for as a child link #}
{% macro listCategoryPages(catID, level) %}
    {% set categories = craft.categories.group(catID) %}

    {% nav category in categories %}
    {% set active = category.url == url(craft.request.path) ? ' active' : '' %}
    <li class="level{{ level }}{{active}}">
        <a href="{{ category.url }}" title="{{ category.title }}" class="level{{ level }}{{active}}">{{ category.title }}</a>
    </li>
    {% endnav %}
{% endmacro %}

{% macro addPageToNavigation(page, level) %}
    {# category listing, represented by one child link #}
    {% if page.url starts with '%%category%%' %}
        {{ _self.listCategoryPages(page.url|replace('%%category%%', ''), level) }}
    {# normal listing #}         
    {% else %}
        <li class="level{{ level }}{% if page.active %} active{% endif %}">
            <a href="{{ page.url }}" title="{{ page.name }}" class="level{{ level }}{% if page.active %} active{% endif %}">{{ page.name }}</a>

            {% if page.children is defined %}
                <ul class="sub">
                    {% for subpage in page.children %}
                        {{ _self.addPageToNavigation(subpage, level+1) }}
                    {% endfor %}
                </ul>
            {% endif %}

        </li>
    {% endif %}
{% endmacro %}

<nav class="primary-menu">
    <ul class="level0">
        {% for page in nav %}
            {{ _self.addPageToNavigation(page, 0) }}
        {% endfor %}
    </ul>
</nav>

This will allow you to add a menu item with the url '%%category%%fruits-veg' (and i've named it "Category: Fruits and Vegetables" but the name isn't used) and the template will replace it with the full (non-hierarchal) listing of the fruits-veg category.

I hope that helps others :)

engram-design commented 9 years ago

Thats awesome @alexbrindalsl. It'd be great to have this a bit user-friendly for clients to choose, but will certainly do for now! :)

hubertprein commented 9 years ago

Added category support in the latest release.

engram-design commented 9 years ago

@hubertprein Thats awesome - great work!