Sites with loads of pages can be hard to manage. Includes were the gold pot in the end of the rainbow times ago so people could put repeated content (like headers, footers and menus) under a single file and thus including into the page/template.
But have you ever wondered that you keep having the same include occurrences at the pages? The layout concept (that I first saw under CakePHP [but it may have come from Rails actually]) brings you more flexibility and DRYness on working with templates.
When the pixel-painters (designers) produces a layout, it basically follows the same structure changing only part of the template per page (the content area) so why not making a whole package with it and produce template files containing only the content that will actually change. Let’s take a closer look.
Now, in most web applications, the template files (like index.php for example) usually have a repeated sequence (like header,menu,content,footer in the example).
NOTE: I use Smarty for handling my template files (.tpl) but I’ll use .php files in order to exemplify in a wider view.
Imagine the following page (example in HTML+PHP):
<?php include 'header.php'; include 'menu.php' print "<div id='content'>"; /* here goes our content */ print "</div>"; include 'footer.php'; ?>
You see? Try to go further and imagine this code snippet being repeated times and times over your dozens or hundreds of pages. Not cool, huh?
Well, the layout concept concentrates those repeated content under a layout template file with a holder for the content to be included. This can be a variable in a templating system or a wildcard to be string-replaced later on.
Here are some examples
Smarty
<?php $Smarty = new Smarty(); $content = $Smarty->fetch('my_content_template.tpl'); $Smarty->assign("content",$content); $Smarty->display("my_layout_template.tpl"); ?>
String-replacement
The Template
<!-- header and menu includes above here --> <div class="content">%mycontent%</div> <!-- footer includes below here -->
The layout tpl file would have a {$content} variable that will be replaced by my actual content.
The code (PHP)
<?php $layout = file_get_contents('my_layout_file.html'); $content = file_get_contents('my_content_file.html'); $layout = str_replace('%mycontent%',$content,$layout); // content replacement print $layout; // show the complete page ?>
This gives you the advantage of switching quickly layouts while preserving the very same content template.
Quick and easy! This comes to be very handy when generating print, mail and other versions of your content.