Quantcast
Channel: Antanova Ltd. » php
Viewing all articles
Browse latest Browse all 2

ASP.net style master pages in PHP

$
0
0

I’m not a .net developer. A few months ago, though, I was building a mini site for a property company, who’s hosting was on a .net server. I thought I’d have a go at using master pages instead of several different include files.

What a revelation! I really like the way that you specify a page that’s to be used as the template for the site, and simply add some place-holders that are to be populated with the content from your individual local pages. The whole thing then hangs together very nicely. You can even use relative links that are re-written by the server so no matter where you content page is, the link is always pointing at the same file. The code is clean, too, as the master and content pages are all marked up using XML, so all your code looks nice and is easy to follow in your editor of choice.

A different, but equally small site has now come up and it’s got me thinking about how to implement something like this in PHP. Now, there are several templating systems already out there for PHP, for example Smarty. I didn’t want to use one of those, because like I said the site’s very small, and adding all those extra files in there and using the Smarty syntax would just unnecessarily increase the development time for such a small site. So, I set about making something up myself.

I’m pretty pleased with what I came up with: it’s not quite as clean as the .net version, but it is simple and easy enough that it will help rather than hinder the development of such as small site. I’ve got my template (the ‘master’ page) on which I’ve defined a couple of areas where the content is to be dropped in.

template.php:

<?php Header("Content-Type: text/html; charset=UTF-8"); ?>
<html>
  <head>
    <title><?php echo $page->title; ?></title>
    <link rel="stylesheet" type="text/css" href="/path/to/stylesheet.css">
    <?php echo $page->head; ?>
  </head>
  <body>
    <nav>
      <ul>
        <li><a href="/">Nav item 1</a></li>
        ...
        <li><a href="/">Nav item n</a></li>
      </ul>
    </nav>
    <div>
      <?php echo $page->content; ?>
    </div>
    <footer>
      footer message here
    </footer>
  </body>
  <?php echo $page->foot; ?>
</html>

page.php:

<?php
$page->title    = "Hello, world";
$page->template = "template.php";
?>
<?php ob_start(); /* head   */ ?>
  <meta name="description" content="description here">
<?php $page->head = ob_get_clean(); 

?>
<?php ob_start(); /* content*/ ?>
  <h1>The Page Title</h1>
  <p>The article goes here</p>
<?php $page->content = ob_get_clean(); 

?>
<?php ob_start(); /* foot   */ ?>
  <script type="text/javascript"> ... /* page specific script */ </script>
<?php $page->foot = ob_get_clean(); 

?>
<?php include_once $page->template ?>

Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images