Skip to content

Instantly share code, notes, and snippets.

@hgraca

hgraca/run.php

Created Jul 21, 2020
Embed
What would you like to do?
A very simple template rendering mechanism.
<?php
declare(strict_types=1);
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:
//<div>
// <h2>Hello world!</h2>
// <p>A very simple template rendering mechanism.</p>
//</div>
<div>
<h2><?php print $title; ?></h2>
<p><?php print $content; ?></p>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.