Last active
February 7, 2023 11:39
-
-
Save philippgitpush/a2173ef5b89d7c11325439795bd77d90 to your computer and use it in GitHub Desktop.
Dynamic template rendering in PHP
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 | |
// Following object is empty, this should be filled from a DB or CMS | |
$page = new stdClass(); | |
// Example of using a template file | |
function renderTemplateFile($templateFile, $variables) { | |
// Start a new output buffer | |
ob_start(); | |
// Extract variables into the current symbol table | |
extract($variables); | |
// Include the template file | |
include $templateFile; | |
// Return the contents of the output buffer | |
return ob_get_clean(); | |
} | |
// Example single markup | |
$article = renderTemplateFile('./path/to/templates/article.tpl.php', array( | |
'title' => 'Example title', | |
'description' => 'Example description', | |
)); | |
// Example multiple markup | |
forearch ($page->buttons as $button) { | |
$buttons .= renderTemplateFile('./path/to/templates/button.tpl.php', array( | |
'title' => $button->title, | |
'href' => $button->url, | |
'external' = true | |
)); | |
} | |
?> | |
<!-- Example Output --> | |
<section> | |
<?= $article ?> | |
<?= $buttons ?> | |
</section> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment