-1

I'm trying to create a navigation on my webpage however using php templates for the nav makes it difficult to add the active class to the right page.

For example, if my php file is the below:

    <nav>
        <ul>
            <li><a>Home</a></li>
            <li><a>About</a></li>
            <li><a>Contact</a></li>
        </ul>
    </nav>

How do I give each page the class .active?

The only alternative I can see is giving either <html> or <body> a class of each page name on that specific page.

Spedwards
  • 4,167
  • 16
  • 49
  • 106
  • If you display the correct content of the requested URL then you have all the info to loop over the navigation and add the class at the correct item. What template/framework do you use? – Stefan Jul 09 '14 at 15:11
  • You could use a PHP variable unique to each page. Like, $pageTitleIs='ThisPage'; Then use THAT to tell what page you're on. – durbnpoisn Jul 09 '14 at 15:11
  • 1
    Try searching before asking. http://stackoverflow.com/questions/6741977/php-navigation-menu-and-active-page-styling?rq=1 http://stackoverflow.com/questions/13336200/add-class-active-to-active-page-using-php?rq=1 http://stackoverflow.com/questions/18244449/show-active-navigation-for-current-page-with-php?rq=1 http://stackoverflow.com/questions/19387470/php-based-on-which-page-im-on-change-the-active-class?rq=1 http://stackoverflow.com/questions/19463730/global-navigation-with-active-selector-php?rq=1 http://stackoverflow.com/questions/21254404/class-active-when-on-page-using-php?rq=1 – Lawrence Cherone Jul 09 '14 at 15:12
  • @LozCheroneツ I always try to search before asking but sometimes it's hard when you don't know what to search for. – Spedwards Jul 09 '14 at 15:20
  • Also dont ignore the `Questions that may already have your answer` as you type your question, *it searches for you* – Lawrence Cherone Jul 09 '14 at 15:24
  • @LozCheroneツ I don't ignore it. – Spedwards Jul 09 '14 at 15:28

1 Answers1

0

Here is a pretty not great way to do it:

<?php
function ap($pagename) { if($pagename === $current_page) return ' class="active"'; return ''; }
?>
<nav>
    <ul>
        <li<?=ap('Home')?>><a>Home</a></li>
        <li<?=ap('About')?>><a>About</a></li>
        <li<?=ap('Contact')?>><a>Contact</a></li>
    </ul>
</nav>

Maybe try using a templating engine (smarty).

beiller
  • 3,105
  • 1
  • 11
  • 19