2010-05-07 65 views
2

一段時間以來,我一直使用下面的代碼來動態地在html頁面標題中編寫代碼,併爲菜單項添加一個活動類。這仍然是一個很好的爲什麼要實現這一目標,或者有更好/更聰明/最佳的方式來實現相同的事情?動態地使用php編寫頁面標題和活動類

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

菜單例如

<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> 

頁標題例

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

回答

1

,你可以將其寫入功能。

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> 
+0

你甚至可以用功能創建整行...... – Dormilich 2010-05-07 11:59:00

0

這不是一個壞的方法。我用一個循環來做,所以輸入的次數減少了。例如:

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"; 
}