Monday, September 16, 2013

Simple tip to manage the layout of a site in PHP

Update (02 dec 2013)

In this post I will describe the simple method I use to manage the layout of a website using PHP. Probably there are better solutions, but I prefer this way because I think it's simple and intuitive; obviously, any suggestion or criticism (possibly constructive) is well accepted :) .

The layout file

First of all you need to create a php file in your site's root directory that will define the layout of the site. You can name it, for example layout.php. Once created it you can design in it the layout of your site, using this structure:

<!DOCTYPE html>
  <!--Shared head: scripts, stylesheets,... -->
  <link href="/style.css" rel="stylesheet" type="text/css">
  <script src="/jquery.min.js"></script>
  <!--End of the shared head -->
  <?php getHead(); ?>
  <!--The site's layout (example: title, menu and footer) -->
                <ul id="menu"><li>1</li><li>2</li><li>3</li></ul>
  <!-- Put the following php line where you want to load the page's content -->
  <?php getBody(); ?>

The site's pages

Now we've created a PHP files that calls the two functions getHead() and getBody(), but where are they defined? Simple: they will be defined in each page file, because any page file will be structured as this:

<?php function getHead(){ ?>
<!-- Page's title and other head elements of this page -->
<title>My page</title>
<?php }
function getBody(){ ?>
<!-- Page's content -->
<p>Hello, world!</p>
<?php } 

As you can see, at the end of the file the script includes the layout page, so your page will be displayed in the layout that you previously created; if you put the pages in subdirectories of the web root, remember to adjust the reference to the layout file (for example, ../layout.php instead of layout.php).

No comments:

Post a Comment