0

I'm building a website which uses a lot of repeated styles and HTML tags, such as the header, the navigation bar at the top, and the footer at the very bottom. Instead of typing all of that repeated code in again and again, I'd like to use PHP include statements to include everything that I need.

While that's all well and good, this poses a problem with my navigation bar. I use a CSS class attached to the navigation link to let the user know what page they're on (using a different background color). On each page, I manually specify which link gets that special class. If I were to simply include that content via a PHP include statement, I couldn't manually specify the class.

My question is: how would I be able to do that? Either by using a separate PHP script to find out which page the user is on, and then specify the class to style the link appropriately, or by using JavaScript to do the same thing? Or maybe there's something else that I'm missing? Who knows! And as such, I ask!

2

1 Answer 1

2

An easy way to do it would be to add a PHP variable like $page before the include and then use this variable in your included menu file to determine which menu item needs highlighting.

So in the file with the includes:

$page = "home";
include("menu.php");

And in the menu file:

<ul>
    <li <?php if( $page == "home") echo 'class="active"' ?> >home</li>
    <li <?php if( $page == "about") echo 'class="active"' ?> >about</li>
    <li <?php if( $page == "contact") echo 'class="active"' ?> >contact</li>
</ul>

The example above isn't the tidiest or most optimal solution, but it gives you an idea of how you could achieve what you are trying to do by using PHP variables.

Sign up to request clarification or add additional context in comments.

1 Comment

minor typo correction; the echo statements are not closed by an end quote ( ' )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.