Jump to content

Current page selected


ZionBludd
 Share

Recommended Posts

I am wondering how I would go about getting PW to put a class="list-group-item active" class onto the page that is active.

Here is my code currently 

<?php
//$getStaticPages = $pages->get("/about"); 
$staticPages = $about->children("sort=name");

foreach($staticPages as $staticPage) {?>
<li class="list-group-item"><a href="<?=$staticPage->url?>"><?=$staticPage->title?></a></li>

<?}?>

I'd appreciate any help :) 

Link to comment
Share on other sites

This should do it. Sorry for reformatting your code, but it becomes awkward trying to add ternary operators into a code block with PHP tags sprinkled into the HTML like that.

$staticPages = $about->children("sort=name");

foreach($staticPages as $staticPage) {
    echo "<li class='list-group-item" . ($page == $staticPage ? " active" : "") . "'><a href='{$staticPage->url}'>{$staticPage->title}</a></li>";
}
Link to comment
Share on other sites

This should do it. Sorry for reformatting your code, but it become awkward trying to add ternary operators into a code block with PHP tags sprinkled into the HTML like that.

$staticPages = $about->children("sort=name");

foreach($staticPages as $staticPage) {
    echo "<li class='list-group-item" . ($page == $staticPage ? " active" : "") . "'><a href='{$staticPage->url}'>{$staticPage->title}</a></li>";
}

Thank you. This worked. Still learning PHP, hence the messy code :) 

Link to comment
Share on other sites

No problem at all - there is nothing wrong with the approach you took - completely valid code and appropriate in many cases so long as you don't need additional logic.

Since you're new to PHP (and maybe other scripting languages?), you may not have seen ternary operators before, so here is a great explanation: http://davidwalsh.name/php-shorthand-if-else-ternary-operators

They shouldn't be used instead of if/else in all situations, but in many cases they can make code simpler. If used incorrectly with too much nesting, they can become horrible to read :)

If you want to stick to the style you have, you could do this:

$staticPages = $about->children("sort=name");

foreach($staticPages as $staticPage) {?>
<li class="list-group-item<?=$page == $staticPage ? " active" : ""?>"><a href="<?=$staticPage->url?>"><?=$staticPage->title?></a></li>

<?}?>

I find it messier, but others may prefer it.

Also be warned about php shorttags: <?= vs <?php echo - not all servers will currently support shorttags, although it is the default in more recent versions of PHP.

  • Like 2
Link to comment
Share on other sites

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
 Share

  • Recently Browsing   0 members

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