简体   繁体   中英

add class to body based on browsed page with PHP?

i'm working on my own php project ad learning php and i was trying to get the body to add class by the page name like:

<body class='homepage'><!-- for index.php -->
<body class='single-post'><!-- for posts.php -->

my code:

<?php include "header.php";?>
<?php include "post.php";?>
<?php include "footer.php";?>

UPDATE

i tried and make it work myself by

<?php 
    $classone = $_SERVER['REQUEST_URI'];
    if(strpos($classone, 'index') != false){
        echo "<body class='homepage'>";
    }else{
        echo "<body>";
    }
?>

but i'm hoping if there's any function on php can do the work or a better way to do it

Kind of a vague question, but I think I understand what is being asked. The page name has be extracted from the request and ran through a lookup table to get the desired class name for the body.

The page file names can be found in the $_SERVER array using the PHP_SELF index, so with the pathinfo function, the name can be easily extracted.

$page_name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);

Next, a lookup table is required, to translate the $page_name into a css class name. I strongly discourage this practice as it can lead to confusion. Best to keep the class and page names consistent with each other for better maintainability and a less brittle product.

If you have new PHP (>=5.4)(which you should be using a newer version):

$class_lookup_table = [
  'index' => 'homepage',
  'posts' => 'single-post'
];

If you have old PHP (<5.4)

$class_lookup_table = array(
  'index' => 'homepage',
  'posts' => 'single-post'
);

Now you can reference the class name in the HTML

<body class="<?php $class_lookup_table[$page_name] ?>">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM