Collect all lowest level descendants

I have a page that has children, and those children have children (see example structure below). I want to display all the level 3 pages together in one place.

 level 1 page
    level 2 page
        level 3 page
        level 3 page
    level 2 page
        level 3 page
        level 3 page

I tried using taxonomy to do this, by giving all the level 3 pages a common tag or category and creating a collection of that tag/category, but the collection included the level 2 pages, as if they were taking on their child page taxonomy.

Now I’m trying to use a for loop to go through each level 2 page one by one and output all child pages. As shown below.

{% set options = { items: {'@page.children': '/level1page'} } %}
{% set lvl2_collection = page.collection(options) %}

{% for lvl2page in lvl2_collection %}

	{% set options = { items: {'@page.children': '/level1page/{{ lvl2page.title|lower }}'}, 'order': {'by': 'date', 'dir': 'desc'} } %}
	{% set lvl3_collection = page.collection(options) %}

		<div>
			{% for lvl3 in lvl3_collection %}
				<div>
					{% lvl3.content %}
				</div>
			{% endfor %}
		</div>

{% endfor %}

For some reason this returns an empty collection (no content). I think the problem is where I include {{ lvl2page.title|lower }} in the options for the second collection. If I replace that with the title of the first level 2 page (typed out) it creates a collection no problem, but I need this to change for each cycle of the first for loop so it goes through all the level 2 pages.

Is there a way to do this, or a totally different method for collecting all the level 3 pages? Any help is much appreciated!

Hi jego,

try this, it should work:

{% for p in page.collection %}
{% if loop.index > 2  %}
    ...
{% endif %}
{% endfor %}

with the loop.index > “Number” you actually set the index you want show(your level) - it shows also all deeper levels so in case, that your structure get more “levels” you should adjust ist or combine it with another condition

Maybe you should do that with a plugin which uses PHP to build a collection where all pages with no children are collected.

See: https://learn.getgrav.org/cookbook/plugin-recipes#iterating-through-pages-and-media and https://learn.getgrav.org/content/collections#php-collections

Thanks for the help guys. After posting the question I ended up restructuring the page hierarchy to fix the issue.

ehllo - I went ahead and marked your reply as an answer because I’m pretty sure what you’re saying would’ve worked for this situation.