Skip to content

Instantly share code, notes, and snippets.

@samnabi
Created June 7, 2015 10:39
Show Gist options
  • Save samnabi/19f92bd7b585ba07a77f to your computer and use it in GitHub Desktop.
Save samnabi/19f92bd7b585ba07a77f to your computer and use it in GitHub Desktop.
showIndex for Kirby
<?php
/**
Translates Kirby's index() function to a nested list by building a string of markdown text then converting it to HTML. Useful for navigation menus of unknown depth.
@param must be an index() object
@return string of HTML
*/
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.
$level = $page->depth() - $intial_level - 2;
if ($level > 0) {
$prefix = str_repeat(' ', $page->depth() - $intial_level - 2);
} else {
$prefix = '';
}
// Manually build the output string in kirbytext/markdown format
$count = $page->children()->filterBy('template','product')->visible()->count();
$output .= $prefix.'- <a href="'.$page->url().'" title="'.$page->title().'"';
if ($page->isOpen()) $output .= ' class="active"';
$output .= '>'.$page->title();
if ($count) $output .= '<span>'.$page->children()->filterBy('template','product')->count().'</span>';
$output .= '</a>'."\n";
}
// Return the list as HTML
return kirbytext($output);
}
?>
@samnabi
Copy link
Author

samnabi commented Jun 7, 2015

Put this file in your plugins/ folder, then use it in your templates like this:

$categories = $pages->index()->filterBy('template','category');
echo showIndex($categories);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment