CSSgallery.info

Image crop tool
18  01 2008

php “included” menu styling


Some times , when we have a pretty big amount of pages on a site, but don’t need or want to use a CMS, we take advantage of PHP and split the page layout in more includes like:header.phpcontent.phpfooter.phpso we do not need to write the same content ( or copy paste :D ) in every page.If our design is oriented to user( i mean it try to have some usability ) we’ll need to find a way to make the menu clear - pages that are active needs to be “highlighted” somehow.a good example is in wordpress :menu highlighted“Posts” page is current page.We can do this the hard way - copy menu content in every page, and change the styling for current link,or use some php code that do this for us, and move the menu in “header.php” include file.This is a small code we can use for our needs:

<?php $domain = $_SERVER['HTTP_HOST']; $url = "http://" . $domain . $_SERVER['REQUEST_URI'];?>
 
<p class="actual_menu">    
 
<a href="index.php" class="<?php echo (( $url=="index.php") ? "menu_on" : "menu")  ?>">Home</a>
 
<a href="product.php" class="<?php echo (( $url=="product.php") ? "menu_on" : "menu")  ?>">Product</a>
 
<a href="directory.php" class="<?php echo (( $url=="directory.php") ? "menu_on" : "menu")  ?>">Directory</a>
 
</p>

The above code will work for relative links, for absolute links you will have to detect the full url of current page:

<?php $domain = $_SERVER['HTTP_HOST']; $url = "http://" . $domain . $_SERVER['REQUEST_URI'];?>
<div class="actual_menu">    <a href="http://www.cssgallery.info/index.php"
	class="<?php echo (( $url=="http://www.cssgallery.info/index.php") ? "menu_on" : "menu")  ?>">Home</a>
</div>

3 Responses to “php “included” menu styling”

  1. > We can do this the hard way - copy […]

    Sorry, but your way is the hard way. Look how often you copied the same code. Further you do not seperate logic with view code, which eventually become a maintainance nightmare…

    You are on the right way, though. “Don’t repeat yourself” is not only valid for CSS/HTML Code, especially you have to apply it to your PHP code.

  2. For Chris:

    I do not understand why you say it’s this the hard way. I applied this idea on a site and it seems easier to have just one menu.php file with that code or include it in the header file.

    It’s so easy that even my client can update the menu all by himself by editing just ONE file instead of X files.

    If you have another solution, please share it with us.

    Thank you,

  3. You are right: It is easier to have just one menu.php file.

    So you made the step and refactored the code from multiple files into one file. Now go a step further and look how often your wrote the same code in menu.php.

    1. DRY up your code (http://en.wikipedia.org/wiki/Don%27t_repeat_yourself)
    2. Then move your logic out of the presentation code.

Leave a Reply

« Rounded corners generators Javascript rounded corners »