A Simple Yet Powerful PHP Template Engine

If you are in hurry, skip this to the meat.

It has been a while now since my last posting to this website. Due to busy schedule of my life I wasn't able to keep up the posting. While from the web stats I see quite large number of people coming to this website, I sincerely apologize for my inactivity.The main purpose of this website, as always, is to share programming goodies. So today I am going to toss you another one: my home-grown PHP template engine.

This is not yet another regular expression replacement template engine. The template engine uses PHP itself to render the template. The template itself is very intuitive to people who are already familiar with PHP. There is no extra learning for additional syntax - the template code itself is just plain PHP code. Though I haven't done any benchmark, from my past experience of using it, it is pretty fast - consider that it consists of less than 100 lines of code. Thinking of using Smarty?

In case you are not familiar with the idea of using templates in web development, here's a little brief: it's a practice of separating the presentation part of your code from the main flow of your code. Just to make your code more reusable and easier to read.


Quick Start

Here's our template file hello.php:

Load a template and assign variables to it, and render it:

That's it. You choose the template you want to render, and assign values to variables in the template. You now can use this presentation code for whatever purpose you want.


The Code

Let's take a look how it works.

ctTemplate is the template engine class. It provides methods to load and render the PHP template. The first parameter of loadTemplate is the name of template you want to load, the second parameter is the variables you want to set in the template. After it has been called, loadTemplate returns rendered code.

The template is rendered in an isolated environment, meaning that the variables in the template will not collide with the variables from the context where the template is loaded. For example, let's use the hello.php template above:


Examples

Example 1

Load template and output it in one function call:

Example 2

Combine different templates:

Content of layout.php

Content of hello.php

Example 3

Customize these options based on your needs:

Available Functions

Below are the methods exposed to public:

Download

Source Code

Please report any bugs you find in this script so I can improve it in the future. Any suggestion or idea are welcome. Just use the comment feature below. Thanks for reading.

5 Comments A Simple Yet Powerful PHP Template Engine

  1. whatever

    Seen it before a thousands of times, stop re-inventing the wheel. Honestly, just stop.

Comments are closed.