Search code examples
phphtmlserver-side-includes

PHP equivalent to site.master?


One of the nice things about ASP.Net is the ability to set a site.master file that holds all the repeated HTML/code from a site, and still be able to alter things on it from an individual website page. (For example, changing the <title> tag for every page, or adding other things to the <head> of your document.)

In the past in PHP I've used Server Side Includes to remove duplicate HTML/code (such as the top of the document, main navigation, footer, etc.) but obviously you can't alter any of the contents from the page.

Is there any way to implement site.master type functionality in PHP? If not, what's a good way to remove repeated HTML/code while still being able to change things like the page's title, highlighted navigation, etc.

Thanks.


Solution

  • The simplest way of pulling in common fragments is to use require() which will allow you to include other files within the current file.

    An example of how you might use it:

    header.php - a reusable fragment

    <div class="header">
        <h1><?= $pageTitle ?></h1>
    </div>
    

    pageContents.php

    <body>
    <?php
    $pageTitle = 'Check it out, the Foobar page!';
    require('header.php');
    ?>
    blah blah
    </body>