Created
July 21, 2020 12:50
-
-
Save hgraca/c638665ea57f1cc3d427d445b4c9d4fc to your computer and use it in GitHub Desktop.
A very simple template rendering mechanism.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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