Osama Kakhia

a story of life

Posted: 2008-09-26 13:23:22
Comments:Add Yours | View

PHP Template Generating Engine

How to parse a template file? You'd face this question with every programming of a php script. Imagine you are programming multi-language forum for example. What would be easier, designing different html pages for each language, or just create a master template file and parse the content according to the selection of a certain language?
Second option would naturally be the choice, but how to!
It's very simple with php by using the regular expression function "preg_replace_callback". Following is how to use it.

Before looking into the code, let's start with creating some constants. These constants are the static text which would appear on the output page for the user. In our example of programming a forum, these constants are the language words or phrases. For creating a multi-language page, you just modify these without having to touch the template file nor the php code.
Create a php file "english.php" with its content like:

<?php
    $constant['title'] = 'My Home Page';
    $constant['content'] = 'Welcome to my page';
?>

Now how to design the master template file! Create it with your favorite HTML design program as if you're designing a normal html page and pay attention to two guidelines:
1. Replace all the static text or phrases with a small code between two % chars
(e.g. %title%).
2. Put the variables between two $ chars (e.g. $date$).
Here is an example of our simple template file "template.htm" :

<html>
    <head>
        <title>%title%</title>
    </head>
    <body>
        %content% - $date$
    </body>
</html>

Did you notice the %title%, %content% and $date$ ?

Thus, we are ready. Lets have a look at the php code. The code contains 3 functions: getfile, replace_const and replace_var.
The main one is "getfile". Its' function is going to retrieves our template file and parsing it. If the function finds any instance of the %constant% or $variable$ in the template, it would pass that match to "replace_const" & "replace_var" respectively.
As their names sounds, each function of the last two would replace any instance of the temporary constant or variable with the "real" data from our php script. Once all temporary constants are being replaced, the main "getfile" would return a string which contains the html page supposed to be send to the user. Here you just output "echo" the string.

// Parse a template file and return it as a string
function getfile($file) {
    // Let's get the template file, and assign the value to a string
    $string = file_get_contents ($file);
    // Replace all %constant%
    $string = preg_replace_callback ( '/%(w+)%/i', "replace_const", $string);
    // Replace all $variable$
    $string = preg_replace_callback ( '/$(w+)$/i', "replace_var", $string);
    // return the final page
    return $string;
}
// Replace constants in the the template
function replace_const ($matches) {
    // the array $constant which we created first above, has to be defined as GLOBAL, else it wouldn't work
    global $constant;
    // Get the index name of the array. Between the % % (e.g %title% => title) and assign it to a temp variable
    $temp = $matches[1];
    // Get the value of the above index, and return it.
    return $constant[$temp];
}
// Replace PHP variables in the template
function replace_var ($matches) {
    // Assign the name of the variable to a temp variable
    $temp = $matches[1];
    // Define the variable as GLOBAL, else it wouldn't work
    global ${$temp};
    // return the value of the variable, ${$temp} does the trick
    return ${$temp};
}

Save the above function to a php page "test.php" and you're done. Thus, how to use this code to parse our template file "template.htm" which we have created above! As you remember we have already created a php page "english.php" that contains the language constants %title% and %content%, but what about the variable $date$ !.
Let's modify the last php page "test.php", here is how it would be:

<?php
// include the language file which contains the constants
include "english.php";

// assign value to the $date var ($date$ in our template)
$date = date("Ymd");

// Now let parse our template file, and assign the returned value from "getfile" to a variable
$string = getfile("template.htm");

// that's all folks! Now let's send the page to the user
echo $string;

###########################################
//of course we wouldn't forget to include the functions :)

function getfile($file) {
    $string = file_get_contents ($file);
    $string = preg_replace_callback ( '/%(w+)%/i', "replace_const", $string);
    $string = preg_replace_callback ( '/$(w+)$/i', "replace_var", $string);
    return $string;
}

function replace_const ($matches) {
    global $constant;
    $temp = $matches[1];
    return $constant[$temp];
}

function replace_var ($matches) {
    $temp = $matches[1];
    global ${$temp};
    return ${$temp};
}
?>

Important note: both the %constant% and $variable$ has to be declared as GLOBAL and their values must be assigned before starting to parse the template.

Before we finish here there is another important note. Do NOT include php code within the template file as it would not be executed. Our function "getfile" is different from the classic "include". The last one imports a file and executes the php codes within it, but our "getfile" import it as normal text and return the value to a string.
Advanced programmers can realize it's possible to modify our "getfile" to make it executes a php code inside using the function "eval". But a drawback of "eval" it is not possible to catch a parse error using "set_error_handler". Peronally I would avoid using it here.



Add Your Comments:

Username:
Email: Hide my email from public
Comments:
Security Code:


 Audio
 Reload Image

 
No comments yet! Be the first to add yours