Support Forums
[TUT] Web Template System - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: PHP The Hypertext Preprocessor (https://www.supportforums.net/forumdisplay.php?fid=21)
+---- Thread: [TUT] Web Template System (/showthread.php?tid=16072)

Pages: 1 2


[TUT] Web Template System - Gaijin - 02-08-2011

Basic Template System


Introduction:
In this Tutorial I will show you how to create your own Web Template System, using PHP.
The Engine is very much basic, but it does the work.
This tutorial is meant to give you an Idea on Template Systems and you can code yours.

Requirements:

Basic PHP OOP Knowledge.

What are?
Template Systems allow yoou to split your HTML source into multiple files, giving you the possibility
to reuse the same part again, without the need to write it down again.
They also use lists of keywords, which then are being replaced with content on the scripts execution.
Meaning, you can use same part of the code, more then once and having different content every single time.

So, let's start coding!


We will create a file called "theme.inc.php", this will will be the core of our Template System.
Now let's create a Class (object).

PHP Code:
<?php

class Theme
{
    const 
ROOT "templates";
    const 
EXT "tpl";
    
    protected 
$keywords = array();
    protected 
$output null

Since this is just a basic System, we have all that we need.
The constant "ROOT" will hold the full path to our folder with Template Files.
The constant "EXT" is the extension the files will have, ex: templates/header.tpl would be the path to our header file.
$keywords is an array which will hold words and their replacements.
Finally, $output is an empty string which will be updated during script execution to hold the entire source of our page.

Continuing;
We will use 2 of PHP's overlading methods called, __set and __get.
http://www.php.net/manual/en/language.oop5.overloading.php

PHP Code:
    public function __set($name$value)
    {
        
$this->keywords[$name] = $value;
    }
    
    public function 
__get($name)
    {
        if(
array_key_exists($name$this->keywords))
        {
            return 
$this->keywords[$name];
        }
        else
        {
            return 
null;
        }
    } 

These 2 functions will be called when you assign a value to unexisting property of the class, or when you
try to get the value.
So what we do is, we put the unexsiting property into our keywords list and assign the value.
With __get we just return the value or if the $name doesn't exist an empty string.

Now we can continue with our core;
PHP Code:
    public function display()
    {
        return 
$this->parse($this->output);
    }
    
    public function 
append($name null$parse false$return true)
    {
        if(empty(
$name))
        {
            return 
null;
        }
        
        
$full_path self::ROOT."/".$name.".".self::EXT;
        if(!
is_file($full_path) || !is_readable($full_path))
        {
            return 
null;
        }
        
        
$ctn = @file_get_contents($full_path);
        if(
$parse)
        {
            
$ctn $this->parse($ctn);
        }
        
        if(
$return)
        {
            return 
$ctn;
        }
        else
        {
            
$this->output .= $ctn;
        }
    }
    
    public function 
AddKeyword($word null$value null)
    {
        if(!empty(
$word) && !empty($value))
        {
            
$this->keywords[$word] = $value;
        }
    }
    
    public function 
parse($str null)
    {
        if(empty(
$str))
        {
            
$str $this->output;
        }
        
        foreach(
$this->keywords as $word => $value)
        {
            
$str preg_replace("#\{".$word."\}#"$value$str);
        }
        
        return 
$str;
    }
}

?>

OK, we now have evrything we need for a Template System.
The function display, takes the value of $output and passes it to the function parse, then returns
the parsed string.

The function append, takes 3 arguments, the first is the name of the file which we want to add.
Second argument states if we want to parse the content immediately or if we want to wait until display or parse
have been called.
Third argument let us tell the function, if it should return the contents for further processing or just
add it to $output;

AddKeyword, takes 2 arguments, first defines the word and the second it's replacement in the template files.

Function parsecan take a string to parse as an argument, if it dosn't have one, it will use $output.
It goes through our $keywords array and uses preg_replace to replace words with their replacement values.

That's it, you have an basic working Web Template System.
But how to use it?

Let us now learn to use it, create these files in your templates directory.

header.tpl
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en-EN" xml:lang="en-EN" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>{TITLE}</title>
        <link rel="stylesheet" href="{CSS_PATH}" type="text/css" />
    </head>
    <body>
        <div class="head">Template System Tutorial</div>
        <div class="navi">{NAVI}</div>

footer.tpl
Code:
    </body>
</html>

navi.tpl
Code:
<a href="index.php">Home</a> |
<a href="index.php?ref=sf">SupportForums</a> |
<a href="index.php?page=about">About</a>

about.tpl
Code:
A Basic Template System tutorial, for SupportForums.net.

default.tpl
Code:
This will be our Homepage content <br />
Same as every file, it can be written with HTML

Those are the files we will be using, if you take a look at header.tpl you'll notice things like;
{TITLE}, {CSS_PATH} and {NAVI}, these are the keywords that will be replaced with different content.

So let's take a look at the execution script.

PHP Code:
<?php

include_once "theme.inc.php";

$TPL = new Theme();

$TPL->AddKeyword('TITLE''SF Tutorial');
$TPL->AddKeyword('CSS_PATH''styles/main.css');
$TPL->AddKeyword('NAVI'$TPL->append('navi'));

$TPL->append("header"falsefalse);

if(isset(
$_GET['page']))
{
    
$page htmlentities($_GET['page'], ENT_QUOTES);
}
else
{
    
$page null;
}

switch(
$page)
{
    case 
"about":
        
$TPL->append("about"falsefalse);
        break;
    default:
        
$TPL->append("default"falsefalse);
        break;
}


$TPL->append("footer"falsefalse);

echo 
$TPL->display();

?>

First ofcourse we include our core file, and create an instance of our object. $TPL = new Theme()
Next we add few keywords, TITLE, CSS_PATH and NAVI, using the AddKeyword function, and you may have
noticed that $TPL->append('navi') doesn't use the other 2 arguments as all other calls to this function.
This way we are telling the function that we need the data raw and returned, it will be handled by us. ;)

Now that we are done with adding keywords, we can add files and finally display the content.


Functions used:
array_key_exists()
is_readable()
is_file()
preg_replace()
htmlentities()


RE: [TUT] Web Template System - versx - 02-10-2011

Not bad to be honest, I like it keep it up.


RE: [TUT] Web Template System - mashemaru - 02-10-2011

tnx for sharing, this is what i need in my new project.


RE: [TUT] Web Template System - w00pz - 02-11-2011

Thanks for sharing dude!
it's really usefull Smile


RE: [TUT] Web Template System - Gaijin - 03-07-2011

Glad you like it, if you have any questions, PM me or ask here...


RE: [TUT] Web Template System - The-One - 05-29-2011

This is actually quite cool. Thanks


RE: [TUT] Web Template System - 0xE9 - 05-29-2011

Not a bad tut, I like it Smile


RE: [TUT] Web Template System - begginer - 06-01-2011

Thanks for another great tutorial. Keep it up


RE: [TUT] Web Template System - zZJoennZz - 06-01-2011

YAY! Thanks for this! This may help me in my future site XD


RE: [TUT] Web Template System - Filefinder - 06-01-2011

Really not bad i can use this for some school project in the future.