Apply a specific class/id to current page on menu (PHP)

后端 未结 3 1510
南方客
南方客 2021-01-21 16:12

I have a menu like this:


                      
相关标签:
3条回答
  • 2021-01-21 16:57

    You should:

    1. check the result of strpos() with !== false.
    2. Use $_SERVER['REQUEST_URI'] rather than $_SERVER['PHP_SELF'].
    3. Wrap the code inside a function.

    Something like this:

    <?php
    function get_current($name) {
      if (strpos($_SERVER['REQUEST_URI'], $name) !== false)
        echo 'class="current"';
    }
    ?>
    
    <div id="blahblah" style="blahblah">
      <a <?php get_current('biography') ?> href="http://domain.com/folder/biography"><img style="blahblah" src="blahblahblahblah"></a>
      <a <?php get_current('contacts') ?> href="http://domain.com/folder/contacts"><img style="blahblah" src="blahblahblahblah"></a>
      ...
      ...
    </div>
    
    0 讨论(0)
  • 2021-01-21 17:01

    if the position is 0, then it will evaluate to FALSE in PHP. You should check the return value specifically, i.e. >= 0.

    0 讨论(0)
  • 2021-01-21 17:02

    Instead of strpos(), you could try this:

    <?php $current = basename($path, ".php"); ?>
    
    <a href="blahblah"<?php if ($current == 'biographies') echo ' class="current"'; ?> />
    

    $current is the name of the current file, without the .php extension.

    0 讨论(0)
提交回复
热议问题