Will
Will

Reputation: 723

PHP Determined HTML Classes

I'm trying to determine the best way of using PHP to assign the classes of my tabbed menu items.

What I've read so far on the subject here and elsewhere seems to only determine very simplistic cases. I need to have an active class for the tab when you're on it's page and I also need a disabled class for the tab on accounts without access to that feature (based on a session flag).

Originally, I just echoed out everything like this:

 <?php  
    echo '<li class="some-tab ';if($pageName === "somepage.php"){echo'active';}
            if(!$_SESSION['some_flag']){echo'disabled';
            echo'"><a href="">Link</a>';}
   ?>

But then code shame set in and I'm trying to really start using PHP like templating engine. That said, I do not want to use an actual templating engine.

For any other part of the HTML, hopping in and out of PHP is easy and relatively elegant, but when it comes to getting classes to work, it's feels clunky. It completely pollutes the markup and leaves me with way too much logic in my template.

Like so:

<li class="some-tab <? if($pageName === "somepage.php"){echo'active';} ?></li>

Not terrible but add a few more rules and it becomes a mess.

My first thought is creating an associative array and just echoing it's contents:

<?  if(some condition){
       $class = array("sometab" => "sometab active disabled");
    }
    else{
       $class = array("sometab" => "sometab");
    }
 ?>
<li class="<?= $class['sometab'] ?>"> </li>

But I feel like it may be too clever.

I want to avoid storing information in the body class or as Javascript cookies as suggested by some because I'm not just fetching the URL.

Is there an option I'm missing?

Is a class array appropriate in the slightest? I don't have the experience to know if it's a horrible idea or not.

Upvotes: 1

Views: 60

Answers (2)

Alvaro
Alvaro

Reputation: 41605

Your last option would be the most elegant for me. Anyway, if you can use a MVC pattern with some Framework, I would strongly recommend it to you.

In any case, it is very probable you will have to deal with this stuff at some point inside the template if you dont want to create variables for each CSS style.

Upvotes: 0

rcorrie
rcorrie

Reputation: 921

I think you answered this yourself.

You need a templating engine if you want it to run like a templating engine

With that said, something you might find neat though, is shorthand logic statements:

if($x > 10){echo 'BlahBlah';}else{ echo 'NahNah';}

turns into:

echo ($x>10?'BlahBlah':'NahNah');

these can come in handy in logic gates like the ones you are mentioning

Upvotes: 2

Related Questions