PBBG Snippets

Log In or Register

Pure PHP templating engine

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
This system lets use implement a simple template engine
that uses pure PHP. 

The entire template engine -- it's just one short function:
<?php
function render_template ($template_name, $vars) {
    // fill the local variable scope with the items in $vars
    extract($vars);
    // starts buffering output -- nothing will be sent to output.
    ob_start(); 
    // render the template by including it in the local scope
    include("templates/{$template_name}.php"); 
    // get the output since ob_start(), as a string
    return ob_get_clean(); 
}
?>
How do we put it to use?

script.php
<?php
$vars = array(
    "name" =>  "Sandra",
    "birthday" => "October 1st"
);

// We use the template called "birthday", so this translates into
// a file called templates/birthday.php (see the include() call in template function)
print render_template("birthday", $vars);

?>
end script.php

The $vars array is what we are giving to the template.
We don't touch any HTML in the script!
The template will take care of it.

templates/birthday.php
<html>
<body>
<p>Hello, <?= $name ?>. We can print your name directly as the variable, thanks to the extract() call.</p>
<p>Your birthday is: <?= $birthday ?></p>
</body>
</html>
end templates/birthday.php

You can print out $name and $birthday directly because they were extracted
into the local scope. And you can run any PHP functions in the template.

You can nest templates, as well. Suppose that templates/sidebar.php
contains some HTML to style a sidebar. You can do the following:
<?php
print print render_template("birthday", array(
   "name" => "Joe",
   "birthday" => "October 1st",
   "sidebar" => render_template("sidebar", array(
      "weather" => "Sunny",
   ),
));
?>

Because this uses the native PHP parser, it is blazing fast.
It lacks support for caching, but it can be added.

Comments

luke (on January 20, 2010):

This looks pretty neat! I caught a lot of flak for using Smarty in the Building Browsergames tutorials, but I think I might have to look into something like this for the next round.

You need to be logged in to comment on snippets.