tags:

views:

45

answers:

2

For some time now I've been using the following code to dynamically write in html page titles and add an active class to menu items. Is this still a good why to achieve this or are there better/smarter/optimal ways of achieving the same thing?

<?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='contact.php'? 'class="active"' : '');?>

Menu example

<ul id="nav">
<li><a href="index.php"  target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='index.php'? 'class="active"' : '');?>><span>Home</span></a></li>
<li><a href="services.php"  target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services.php'? 'class="active"' : '');?><?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services-landlords.php'? 'class="active"' : '');?><?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services-sellers.php'? 'class="active"' : '');?><?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services-tennants.php'? 'class="active"' : '');?>><span>Our Services</span></a></li>
<li><a href="for-sale.php" target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='sales.php'? 'class="active"' : '');?>><span>Sales</span></a></li>
<li><a href="to-let.php" target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='lettings.php'? 'class="active"' : '');?>><span>Lettings</span></a></li>
<li><a href="register.php"  target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='register.php'? 'class="active"' : '');?><?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='register-thanks.php'? 'class="active"' : '');?>><span>Register</span></a></li>
<li><a href="contact.php"  target="_parent" <?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='contact.php'? 'class="active"' : '');?>><span>Contact Us</span></a></li>
</ul>

Page title Example

<?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services.php'? 'Services' : '');?>
<?php echo (basename($_SERVER['SCRIPT_FILENAME'])=='services-landlords.php'? 'Services for Landlords' : '');?>
+1  A: 

you could put that into a function.

function menuIsActive ($filename)
{
    echo (basename($_SERVER['SCRIPT_FILENAME']) == $filename)
    {
        echo ' class="active" ';
    }
}

ex.

<li><a href="contact.php" target="_parent" <?php menuIsActive("contact.php"); ?>>Contact Us</a></li>
Dormilich
you could even go as far as creating the whole line by a function …
Dormilich
A: 

It's not a bad way. I do it with a loop so there's less typing. e.g.:

foreach(array($pagenames as $pagename=>$pageaddress) {
  $active= $_SERVER('SCRIPT_FILENAME'])==$pageaddress? 'class="active"' : '';
  echo <li><a href="$pageaddress"  $active target="_parent">$pagename</a></li>\n";
}
dnagirl