Recursive nested page listing

Here’s a plugin I made to display a nested HTML list for all a page’s descendents, no matter how many levels deep it goes.

showIndex.php

    /**
      Function to create a nested list in HTML from Kirby's index()
      @param must be an index() object
      @return string
    */
    function showIndex($pages) {
      
      // Initialize output string
      $output = '';
    
      // Get the initial nesting level
      $inital_level = substr_count($pages->data[0],'/');
    
      // Loop through pages
      foreach ($pages->data as $page) {
    
        // Set the page's indent level. Markdown requires 4 spaces for each level of depth.
        $prefix = str_repeat('    ', $page->depth() - $intial_level - 2);
    
        // Manually build the output string in kirbytext/markdown format
        $output .= $prefix.'- (link: '.$page->url().' text:'.$page->title().")\n";
      }
    
      // Return the list as HTML
      return kirbytext($output);
    }

Have a look at $page->index(): http://getkirby.com/docs/cheatsheet/page/index
And $page->depth(): http://getkirby.com/docs/cheatsheet/page/depth

1 Like

Nice, I didn’t know about depth(). That simplifies some of the code but I still need to use substr_count() to get $initial_level since it’s working with a string, not an object.

Code updated above.

There’s still a hacky offset required to define $prefix, so if anyone has ideas for improvement I’m all ears.