Create a file called layout.php
. Where you want the content to
appear add <?php echo $content ?>
. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<div id="page">
<?php echo $content ?>
</div>
</body>
</html>
This should be placed in the same directory a your scripts.
Now just add the following to the top of every script (or some include the scripts pull in):
<?php require_once 'lib/layout.php'; ?>
My page content. This will be placed where $content is.
Any content outputted in your script will be placed where $content
is outputted. Note I call the default layout file layout.php
but
also the file you are including is called layout.php
. This is why
I put it in the lib directory. To differentiate it. The one in your
root directory is your layout content. The one in the lib directory
is the one attached to this gist that does the magic.
The $title
variable is automatically pulled into the layout scope.
To set the title simply place the following in your script:
<?php $title = 'Home page' ?>
You can place this before or after the layout require.
If you want to change where the layout file is located just set the $layout variable before calling layout. For example:
<?php
$layout = __DIR__.'/path/to/layout.php';
require_once 'lib/layout.php';
?>
This script provides an excellent opportunity to apply a filter to the
entire output. Similar to an after_filter in Rails. Simply add a callback
function to the global variable $content_filters
. You can do this before
the call to layout.php
(so you are defining $content_filters
or after
by simply appending. Example:
<?php
require_once 'lib/layout.php';
$content_filter[] = 'adjust_markup';
?>
The callback should take the HTML as input and return the final HTML. Content
filters only apply to the $content
and not the layout. Also if the layout
is not used then the content filters are not called.
Redirects are automatically handled. If you set the Location header and exit the layout script will automatically avoid rendering the layout and instead just exit.
This script is quite powerful yet flexible and simple enough to copy and modify for your specific needs.
I am fairly new to PHP though and am having trouble understanding how to use the content filters, could you expand your example a little bit?