Skip to content

Instantly share code, notes, and snippets.

@daggerhart
Last active June 30, 2021 14:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save daggerhart/0c37291c8b656628642b to your computer and use it in GitHub Desktop.
Save daggerhart/0c37291c8b656628642b to your computer and use it in GitHub Desktop.
Example of a template function in PHP
<?php
/**
* Simple PHP Templating function
*
* @param $names - string|array Template names
* @param $args - Associative array of variables to pass to the template file.
* @return string - Output of the template file. Likely HTML.
*/
function template( $names, $args ){
// allow for single file names
if ( !is_array( $names ) ) {
$names = array( $names );
}
// try to find the templates
$template_found = false;
foreach ( $names as $name ) {
$file = __DIR__ . '/templates/' . $name . '.php';
if ( file_exists( $file ) ) {
$template_found = $file;
// stop after the first template is found
break;
}
}
// fail if no template file is found
if ( ! $template_found ) {
return '';
}
// Make values in the associative array easier to access by extracting them
if ( is_array( $args ) ){
extract( $args );
}
// buffer the output (including the file is "output")
ob_start();
include $template_found;
return ob_get_clean();
}
@daggerhart
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment