Listing Published Pages In Habari

For the past few months, I’ve been using Habari to power my site, and so far the experience has been a good one. But, sometimes the documentation in the wiki lacks code examples and is therefore difficult to parse. Thankfully, the Habari community provides its users with several support channels to reach out and find answers to their questions. And, that’s exactly how I found the answer to solve my latest theme-related predicament: listing published pages.

Soon after joining the #habari IRC channel and posting my question, a user by the nickname of mikelietz pointed me to k2, one of the themes bundled with Habari, which made use of a $pages variable in its header.php file. Thanks to mikelietz’s help, I was able to track the $pages variable to k2’s theme.php file, and realized the “magic” taking place. By making use of the add_template_vars function, k2 was defining $pages and extending the behavior of the Theme class. So, without further ado, the code:

public function add_template_vars() {
	if(!$this->template_engine->assigned('pages')) {
		$this->assign('pages', Posts::get(array(
			'content_type' => 'page', 
			'status' => Post::status('published'), 
			'nolimit' => 1))
		);
	}
}

» Code taken from k2’s theme.php.

Once you have added the function above to your theme.php file, the $pages variable should become available to your theme. In order to create a very simple navigation listing your homepage and all published pages, you can do the following:

<ul>
    <li>
        <a href="<?php Site::out_url('habari'); ?>">
        Home</a>
    </li>
    <?php 
    foreach($pages as $page):
    ?>
    <li>
        <a href="<?php echo $page->slug; ?>">
        <?php echo $page->title; ?></a>
    </li>
    <?php 
    endforeach;
    ?>
</ul>

If you know of a better, or more proper, way of extending the Theme class, please leave a comment. Hope this helps someone.