Search code examples
phphtmlphp-include

php templating header and footer


For each page on the site I have a header and footer, so I decided to create a template for both then just include them on each page.

<?php include_once("header.php")?>
   contents of the page...        
<?php include_once("footer.php")?>

header.php contains:

<!DOCTYPE html>
<head>
<title>Items Page</title>
<link rel="stylesheet" href="assets/css/item.css">
<script src="assets/css/item.js"></script>
</head>
<body>
    <header>
        contains a navigation bar  
    </header>

footer.php contains:

    <footer>...</footer>
</body>
</html>

The above codes are for the Items page however I also have Users page they both have the same footer and header markup however different linked CSS and JS files. How can change <link> and <script> inside the <head> tag on the header.php include file if the user navigates to the user page, for example: mysite.com/user/blabla.

The correct link for the Users page should be:

<link rel="stylesheet" href="assets/css/user.css">
<script src="assets/css/user.js"></script>

Solution

  • Use this format in all pages

    <?php    
        $page_title = "title_here";
        $cssfiles   = array("path/to/css1.css", "path/to/css2.css", ...);
        $jsfiles    = array("path/to/js1.js", "path/to/js2.js", ...);    
    ?>
    <?php include_once("header.php")?>
       contents of the page...        
    <?php include_once("footer.php")?>
    

    And in header.php

    <head>
        <title><?php echo $page_title;?></title>
        <?php
        foreach($cssfiles as $css){
        ?>
            <link rel="stylesheet" href="<?php echo $css;?>">
        <?php
        }
        foreach($jsfiles as $js){
        ?>
            <script src="<?php echo $js;?>"></script>
        <?php
        }
        ?>
    </head>