2

I have a Structure section with an ordered number of entries under a parent. On each entry I would like to add a status message of the user's current progress... i.e. You are on page 1 of 5 pages.

The total was easy...

{% set total = entry.getParent(entry).getDescendants().count() %}

How do I get the current page (child) number within the total number of children.

Thanks!

1

I assuming the pages are one level down from the parent?

Parent
  | Child (1)
  | Child (2)
  | ... etc

You can do this:

{% set topLevel =  entry.parent %}
{% set totalPages = topLevel.getDescendants().count() %}      
{% set entryIds = topLevel.getDescendants()|group('id')  %}
{% set currentPageNumber = (entryIds|keys)|indexOf(entry.id) + 1 %} 

{{currentPageNumber }} of {{totalPages}}

Basically we're making an array (list) out of just the entry IDs by grabbing the descendants from the parent. Then we use Craft's group function to give us an array, grouped by key (in this case the ID). Since we know the current page's ID, we can find it in the array and return its position. Since arrays are indexed starting with 0, we just add 1 to it.

| improve this answer | |
  • Perfect! Thank you! The explanation was helpful – user1332211 Nov 5 '15 at 18:00
1

You can get the position number within your branch with a craft.entries element criteria model and the following parameters set:

id – to search only in the current branch, pass the current entry's siblings IDs
positionedBefore – set this param to get entries positioned before the current entry

{% set parent = entry.getParent() %}
{% set siblingsIds = parent.getChildren().ids() %}
{% set total = siblingsIds|length %}

{% set positionedBefore = craft.entries.id(siblingsIds).positionedBefore(entry).order('lft desc') %}
{% set position = positionedBefore.total() + 1 %}

{{ position }} / {{ total }}
| improve this answer | |

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.