Search code examples
phpmaster-pages

Nesting PHP (to implement master & content pages)


Here I thought I was being smart. Using PHP, I created a master page, master.php, that injects one of a selection of content pages: content1.php, content2.php, etc. It didn't occur to me that I'd like to be able to use PHP in the content pages.

The master injects content like this:

<?php
if($pageContentHtml != '') {
    echo $pageContentHtml;
}
?>  

Of course, when $pageContentHtml contains any <?php ?> blocks, the page does not render as desired.

I read about using PHP's ob_* functions to buffer the output but I couldn't quite figure out whether this will let me do what I want. Will it? Is this possible?

Sample content.php file:

<div class="row">
<div class="row-centered">
    <div class="col-md-12">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque...</p>
    </div>
</div>
</div>

<div class="row">
<div class="row-centered">
    <div class="col-md-12">

        <?php
            $bookFileNames = array(
                "book-cover1.jpg"
                ,"book-cover2.jpg"
                ,"book-cover3.jpg"
                ,"book-cover4.jpg"
                .
                .
                .
            );

            for($i=0; $i<count($bookFileNames); ++i) {
                echo '<a href="/images/books/' . $bookFileNames[$i] . '" class="book-title" data-toggle="lightbox" data-gallery="book-covers"><img src="/images/books/' . $bookFileNames[$i] . '" class="img-fluid"></a>';
            }
        ?>

    </div>
</div>
</div>

Solution

  • You can use include() or require() to include the content pages, rather than read in their contents. When included, PHP will be processed as normal:

    include('content1.php');