Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Building a Simple PHP Templating Class

, 9 Jan 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
In this tutorial we are going to setup a very simple PHP template class.

In this tutorial we are going to setup a very simple PHP template class. I don't want to bore you with all the information about why use a template class, and stuff like that, I'm sure you already googled that, and thats why you're here, so lets get straight to it. Note: The code in the template is minimal for simplicity purposes, you are free to use this template class as a base for developing your own.

So our templating class needs to have the following functionalities:

  • Load a template file
  • Set values to the variables in the template file
  • Parse the template file into a php variable to use it within other templates
  • Publish the template/ Output to the end user
  1. So the first thing we do is to define our template class with a template variable, and in our construct function we can take in the $file as an argument.
  2. class Template
    {
        private $template;
        function __construct($template = null)
        {
            if (isset($template))
            {
                $this->load($template);
            }
        }
    }

    Notice in our construct function we are taking in an argument, so we can later define our template as:

    $template = new Template("path/to/template/$file");
  3. The next thing we do is to add a function to load the template file, here we would need to check if the file exists and then load it.
  4. public function load($file)
    {
        if (isset($file) && file_exists($file))
        {
            $this->template = file_get_contents($file);
        }
    }

    Note that with our load function, we don't need to define the file when initializing the Template class, we can do it later, like this: (just to give an example scenario).

    $template = new Template();
    if($page == "player")
    {
        $template->load("path/to/$player_template");
    }
    else
    {
        $template->load("path/to/$normal_template");
    }
  5. Now, we have a way to load our template into our Templating engine. Now we need to find a way of setting variables within our template. I used PHP files for the templates so i can also have PHP code within the template file. Take an example, we have a template file template.tpl.php:
  6. <html>
        <head>
            <title>{title}</title>
        </head>
        <body>
            <div id="username">{username}</div>
            <div id="username">{empty_variable}</div>
            <div id="date"><?php print date("d M Y"); ?></div>
        </body>
    </html>

    Notice in our template, we are naming our variables wrapped within {}, we need some way of setting variables from the php code. We can therefore implement a function like:

    public function set($var, $content)
    {
        $this->template = str_replace("{" . "$var" . "}", $content, $this->template);
    }

    We use PHP's string replace function to replace the variable wrapped in {}. so we can call this method to set our title:

    $template->set("title", "Cleverlogic | Simple Templating Class");
    $template->set("username", "user x");
  7. After we have functions to do everything, and now we have finish setting all of our variables. We would need some way to publish this to the screen, we can have a simple publish function like:
  8. public function publish()
    {
        /*
         * Prints out the theme to the page
         * However, before we do that, we need to remove every var 
         * within {} that are not set
         */
        $this->removeEmpty();
        eval("?>" . $this->template . "<?");
    }

    We use eval here because our template may have PHP code, and we want that code to run, then for the template to be published to the end user.

  9. Notice that within our publish function, we called a function removeEmpty(). What this Function does is that it checks for empty variables within our template file, like our {empty_variable} which wasn't set. If we dont remove empty variables, the actual text "{empty_variable}" would be printed to the end user. So our removeEmpty function uses regular expression matching to remove anything wrapped in curly braces within the template file. the function looks like:
  10. private function removeEmpty()
    {
        /*
         * This function would remove all empty variables from the template wrapped in {}
         */
        $this->template = preg_replace('^{.*}^', "", $this->template);
    }

    And there we have a very simple template file.

Here I would like to make 1 more simple but extremely useful addition to our template file:

public function parse()
{
    /*
     * This function grabs a static document and returns the content
    */
    return $this->template;
}

This function simply returns the template, so we can store it in php variables, we can then use templates within templates (inner template), an example of this:

/*Main Template File: main.tpl.php*/
<html>
    <head>
        <title>{title}</title>
    </head>
    <body>
        <div>Please Fill out the form below</div>
        <div id="form">
            {form}
        </div>
    </body>
</html>
/*Inner template: bottle-form.tpl.php*/
<form>
    Enter Bottle Color: <input type="text" name="color" />
    Enter Bottle Size: <input type="text" name="size" />
</form>
<?php
    /*We can now put the form into our main template by doing: */
    $page = new Template("main.tpl.php");
    $page->set("title", "Bottle Information");
    $form = new Template();
    $form->

The output of the above would be a page with our form in it. Usage Scenarios for this would be: Say we have on page design for all our forms, we can use a single template for that page, and then templates for each form. We can then simply just add the required form into the main template.

So, this concludes our simple PHP Template Class. I hope this tutorial was helpful to you. I have attached below a copy of this template class and also a sample project where we use our template class.

Related Content

Resources

Tags

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

JoshuaKissoon
Student Codestorm Guyana
Guyana Guyana
Currently pursuing my M.Tech in Information Security at NIT Warangal, India.
Follow on   Google+

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMohammad Sharify25-Aug-13 6:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150224.1 | Last Updated 9 Jan 2012
Article Copyright 2012 by JoshuaKissoon
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid