2

enter image description here

I need to get the last item that don't have a child. So in this case I need

Mobiltelefoner
Ipad
Køleskab
Vaskemaskine

How to I get the last item that don't have a child without knowing the amount of levels?

1

Have a look at Craft’s nav tag, which allows to recursively iterate through an array of element models. Only output the category title if the category has no descendants.

{% nav category in categories %}
    {% if not category.getDescendants().total() %}
        <span>{{ category.title }}</span>
    {% endif %}

    {% ifchildren %}
        {% children %}
    {% endifchildren %}
{% endnav %}

Another option would be to write a self-calling macro to recursively traverse the tree.

{% macro getBottomMostElements(elements) %}
    {% import _self as self %}

    {% for element in elements %}
        {% if element.getDescendants().total() %}
            {{ self.getBottomMostElements(element.getDescendants(1)) }}
        {% else %}
            <span>{{ element.title }}</span>
        {% endif %}
    {% endfor %}
{% endmacro %}

{% import _self as macros %}
{{ macros.getBottomMostElements(categories.level(1)) }}
  • I've tried the code above, but it doesn't give the result that I want. Even though the entry category has 4 items when I add it to the loop it loops through all the 7 original categories. I'm still getting a flat array.... – Beuschau Jul 6 '17 at 19:59
  • You shouldn't add it to your loop but replace your loop with it. categories has to be an ElementCriteriaModel. – carlcs Jul 6 '17 at 21:01
  • Still no luck @Beuschau? – carlcs Jul 7 '17 at 12:42
  • No still no luck. Please take a look at this image http://imgur.com/a/tdghB – Beuschau Jul 8 '17 at 8:19
  • I tested both of these snippets and they do exactly what you want, output categories that have no children. I am pretty sure you’re passing in the wrong data for categories, which has to be an ElementCriteriaModel prepared to query for categories. Try the snippet with {% set categories = craft.categories %} set and it will work. I see in your picture that you have the field in a Matrix block, so the categories var would need to be set with something like {% set categories = block.myCategoriesFieldHandle %}. – carlcs Jul 8 '17 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.