Last active
June 30, 2021 14:44
-
-
Save daggerhart/0c37291c8b656628642b to your computer and use it in GitHub Desktop.
Example of a template function in PHP
This file contains hidden or 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 | |
/** | |
* 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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source blog post: http://www.daggerhart.com/create-simple-php-templating-function/