Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically insert a CSS class using PHP?

Tags:

css

php

What's wrong with the following code? I would like to dynamically insert "current" CSS class when the respective <li> element is clicked. Thanks!

<?php 
$pg = $_SERVER['PHP_SELF']; 
?>

<section>
    <aside>       
        <nav>
            <ul>
                <li class="<?php if($pg == 'index.php?page=about.php'){echo 'current';} ?>"><a href="index.php?page=about.php">About</a></li>                       
            <li class=""><a href="">Services</a></li> 
            </ul>
        </nav>
    </aside>
<section>
like image 469
Alexa Green Avatar asked May 31 '11 12:05

Alexa Green


4 Answers

Try with:

<?php 
$pg = $_GET['page'];

$allow = array('about.php', 'main.php', 'other.php');
if ( !in_array($pg, $allow) ) {
    $pg = 'default_value';
}
?>

<section>
    <aside>       
        <nav>
            <ul>
                <li class="<?php if($pg == 'about.php'){echo 'current';} ?>"><a href="index.php?page=about.php">About</a></li>                       
            <li class=""><a href="">Services</a></li> 
            </ul>
        </nav>
    </aside>
<section>
like image 124
hsz Avatar answered Oct 05 '22 18:10

hsz


<li class="<?php echo ($_GET['page'] == 'about.php')? 'current' : 'normal'; ?>">
  <a href="index.php?page=about.php">About</a>
</li>
like image 40
Tim Baas Avatar answered Oct 05 '22 18:10

Tim Baas


$_SERVER['PHP_SELF'] doesn't return the $_GET vars (?page=about.php)

like image 30
MeLight Avatar answered Oct 05 '22 18:10

MeLight


$_SERVER['PHP_SELF'] will start with / and will not include the query string.

You should probably check $_GET['page'] instead.

like image 38
Quentin Avatar answered Oct 05 '22 19:10

Quentin