Skip to content

Instantly share code, notes, and snippets.

@philippgitpush
Last active February 7, 2023 11:39
Show Gist options
  • Save philippgitpush/a2173ef5b89d7c11325439795bd77d90 to your computer and use it in GitHub Desktop.
Save philippgitpush/a2173ef5b89d7c11325439795bd77d90 to your computer and use it in GitHub Desktop.
Dynamic template rendering in PHP
<?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