JV’s Power Tips for PHP (1) - Basic Template Theory (Page 3 of 7 )
Back to the above print statement (print <<<END etc.). As a beginning PHP programmer this type of print statement can be used to build simple template driven websites very quickly. Here is a simple template using this concept:
<?php
// N.B. This file is stored as ‘templates/simple_template.php’
Now let's output “Turkey Love” using our new simple_template.php:
<?php
$gBODY = “Turkey Love”;
include_once “templates/simple_template.php”;
?>
This can be improved greatly upon by the use of two simple functions:
<?php
// N.B. This file is stored as ‘functions/global.php’
// ========================================= // Function 1 - Used to append something to a global variable
function out( $str , $var_name = “gBODY”) { // Make this global variable available to this function global ${$var_name}; // <-- This is a variable variable
// Add the input of string to the global variable gBODY // (or any other specified global variable) ${$var_name} .= $str; }
// ========================================= // Function 2 - Used to select a template.
function use_template ($template_name) { if ( is_file(“templates/$template_name.php”)) { include_once “templates/$template_name.php”; } else { echo “The template $template_name was not found!”; } }
?>
Then if we place the above functions in a global function file, the whole thing looks much more elegant indeed.
<?php
include_once “functions/global.php”;
out(“Turkey Love”);
use_template(“simple_template”);
?>
Using this method it is easy to see how we can create any number of templates and store them within the template directory. Let's have a look at this concept using a slightly more complicated template:
<?php
// N.B. This file is stored as ‘templates/complex_template.php’
If this doesn’t make sense to you go back to the function out(). You can see that any input to out() is written to a global variable (specified as a string in the second parameter of the function out()). Hopefully this makes it clear why I created constants using the define function. Essentially because I’m lazy and when I type:
out(“My Menu”,MENU);
It is really the same as typing (with less effort [and more readable] than):