CATEGORIES
FAQ - Categories

FAQ - How to check whether a Category has children

5min
create an array of a category's children and check whether they exist introduction in this tutorial, i'll explain how you can check whether a category has children we'll do this by creating an array of all the category's children and checking whether the size of this is greater than 0, if so then children exist prerequisites you've created a category and added child categories you've understood some of liquid's syntax create an array of the category's children firstly, let's assign an array that will store all of the category's children after we've done this we'll loop over all the categories and check whether they should be added to the array {% assign this category children = "\[]" | parse json %} loop over all the categories now let's use a for loop to cycle through all the categories on the site, at each index we'll check whether the current category's parent is equal to the category we're viewing in the detail view note category last is used to get the last item in an array we use this here to remove the category items from the arrays they're stored in (which contains a simple list number, followed by the category item) now let's look at our loop {% assign this category children = "\[]" | parse json %} {% for category in context exports categories items %} {% assign this = category last %} {% if this parent == category id %} {% assign this category children = this category children | add to array this id %} {% endif %} {% endfor %} within the for loop we're checking two variables this parent this will contain the parent id of the current category in our loop category id this will always be the same in the for loop above and contains the id of the category being outputted in the detailed view now look at the fourth line of code in the example above, you'll notice these two variables are checked against each other, if they are equal then the category item in our loop will be appended to the this category children array so once this loop has finished this category children will contain all of the children within the category we're outputting on our detail layout you could use the size of our newly created array to determine if there are children, this could be done using a simple if statement {% if this category children size > 0 %} output children {% else %} do something else {% endif %}