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
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.