Skip to content

Instantly share code, notes, and snippets.

Created July 21, 2020 12:50
What would you like to do?
A very simple template rendering mechanism.
function render(string $templateFilePath, array $args = []): string
if (!file_exists($templateFilePath)) {
throw new Exception("Template file '$templateFilePath' does not exist.");
extract($args); // extract associative array items into local scope variables
ob_start(); // buffer the output, so we can get it into a variable instead of returning it immediately
include $templateFilePath;
$renderedTemplate = ob_get_clean();
if ($renderedTemplate === false) {
throw new Exception(
"An error ocurred while rendering template '$templateFilePath' with data: \n" . print_r($args, true) . "\n"
return $renderedTemplate;
$data = [
'title' => 'Hello world!',
'content' => 'A very simple template rendering mechanism.',
echo render(__DIR__ . '/someTemplate.php', $data);
// Prints out:
// <h2>Hello world!</h2>
// <p>A very simple template rendering mechanism.</p>
<h2><?php print $title; ?></h2>
<p><?php print $content; ?></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment