Jump to content

Recommended Posts

Posted

Hi folks! PW newb here. I'm trying to make a sidebar menu of sibling pages when I'm in a subsection. So, HTML like:

<ul class="nav nav-pills nav-stacked">
 <li class="active"><a href='/page1'>This page title</a></li>
 <li><a href='#'>/page2</a>Page 2 title</li>
 <li><a href='#'>/page3</a>Page 3 title</li>
</ul>

I gather I can grab a $page->siblings object and iterate through? Can someone give me an example? Also, how best to test for the current page to make it active?

Thank you!

Posted
This should do what you're after:
foreach($page->siblings() as $sibling){
    echo "<li" . (($page == $sibling) ?  " class='active'" : "") . "><a href='{$sibling->url}'>{$sibling->title}</a></li>";
}
 

Written in the browser and not tested, but should be close.

  • Like 2
Posted

Thanks! Here's what I came up with while waiting. Not as succinct, but seems to work.

<h4><?=$page->parent->title?> Navigation</h4>
<ul class="nav nav-pills nav-stacked">
  <?php
    foreach($page->siblings() as $sibling) {
      if($sibling === wire("page")){ $class = 'active'; } else { $class = ''; }
      echo "<li class='{$class}'><a href='{$sibling->url}'>{$sibling->title}</a></li>";
    }
  ?>
</ul>

I like the way you used the ternary operator. I'm going to steal that and trim down my code. Thanks!

  • Like 1
Posted

No problem. It looks like you had it sorted in quick time anyways :)

Just in case you haven't figured it out the difference between $page and wire('page') yet, there is a little explanation starting at this comment:

http://processwire.com/talk/topic/3056-cant-use-input-urlsegment1-in-a-function-is-this-my-php-weakling-status-showing/?p=30044

As Ryan notes, wire('page') can be used anywhere, but is necessary inside a function due to variable scope. Generally though it is a little shorter to just use $page when you can.

  • Like 2
Posted
It's worth mentioning that … wire('any API variable') would in fact work everywhere. So if you only needed to remember one way of accessing API variables, that one would be the most portable.

Awesome. I was wondering about that!

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...