Getting list of child pages from parent
I’m trying to produce a list of sibling pages that exist from within one parent, whilst on a child page of that parent. Essentially the structure is this:
Home
-
Projects
– Project 1
– Project 2
– Project 3
– Project 4 -
About
-
Contact
Say I’m viewing ‘Project 1’. I want to get a list of all sibling pages of that page. I’m struggling to compose the right code to execute that task. Everything I’ve done to date producing a list of the top level pages.
I should mention that this list is being generated on a modular page.
So on the Project 1 page, you want a list of all other projects pages?
Exactly.
I thought it would be easier to quickly mock this up so here it is:
Simply drop this in to your user/pages/
folder and you can see it. I’ve just enabled twig in the page, and done the twig there for simplicity but you can see the logic. Basically the crux of it is this part:
### Siblings
<ul>
{% for p in page.parent.children if p != page %}
<li><a href="{{p.url}}">{{ p.title }}</a></li>
{% endfor %}
</ul>
Simply speaking i’m just asking for the page’s parent, then looping through the children of that parent, skipping if this page is the current page. Give’s you something like this:
http://polydeon.com/monosnap/Project_2__Demo2_2015-03-25_12-03-00.png
you could even do something like:
{% for p in page.find('/projects').children %}
Really there are lots of options and ways of doing this.
Brilliant. Thanks for your help, works perfectly. I’m new to twig and my php skills are rather rudimentary so some of this stuff has proven mysterious. I really need to bone up on my php before I can build rapidly with Grav.
Feel free to join us on our Gitter chat if you want to ask questions. We have a bunch of helpful folks on there: https://gitter.im/getgrav/grav
is there any way to do this in a partial? I see that in the top-level “default.md” file that you have in your example has {% for p in page.children %}
. In the child page “default.md” file the for loop is {% for p in page.parent.children if p != page %}
. What I would like to do is make a partial that I can include on all pages the logic would look like this:
<ul>
{% if this is the top-level page %}
{% for p in page.children %}
<li><a href="{{p.url}}">{{ p.title }}</a></li>
{% endfor %}
{% else %}
{% for p in page.parent.children if p != page %}
<li><a href="{{p.url}}">{{ p.title }}</a></li>
{% endfor %}
</ul>
Maybe I am not able to think right tonight, but I am having a hard time with this one - I cannot find a way to determine if a page is a parent to its siblings.