Create a gist now

Instantly share code, notes, and snippets.

A simple PHP template class.
<?php
/**
* Class Template - a very simple PHP class for rendering PHP templates
*/
class Template {
/**
* Location of expected template
*
* @var string
*/
public $folder;
/**
* Template constructor.
*
* @param $folder
*/
function __construct( $folder = null ){
if ( $folder ) {
$this->set_folder( $folder );
}
}
/**
* Simple method for updating the base folder where templates are located.
*
* @param $folder
*/
function set_folder( $folder ){
// normalize the internal folder value by removing any final slashes
$this->folder = $this->folder = rtrim( $folder, '/' );
}
/**
* Find and attempt to render a template with variables
*
* @param $suggestions
* @param $variables
*
* @return string
*/
function render( $suggestions, $variables = array() ){
$template = $this->find_template( $suggestions );
$output = '';
if ( $template ){
$output = $this->render_template( $template, $variables );
}
return $output;
}
/**
* Look for the first template suggestion
*
* @param $suggestions
*
* @return bool|string
*/
function find_template( $suggestions ){
if ( !is_array( $suggestions ) ) {
$suggestions = array( $suggestions );
}
$suggestions = array_reverse( $suggestions );
$found = false;
foreach( $suggestions as $suggestion ){
$file = "{$this->folder}/{$suggestion}.php";
if ( file_exists( $file ) ){
$found = $file;
break;
}
}
return $found;
}
/**
* Execute the template by extracting the variables into scope, and including
* the template file.
*
* @internal param $template
* @internal param $variables
*
* @return string
*/
function render_template( /*$template, $variables*/ ){
ob_start();
foreach ( func_get_args()[1] as $key => $value) {
${$key} = $value;
}
include func_get_args()[0];
return ob_get_clean();
}
}
<?php
$suggestions = array( 'user-profile-example-template' );
// provide more-specific template suggestions for logged in users
if ( user_is_logged_in() ) {
// provide a generic template suggestion for all users of a given type
if ( user_is_of_special_type() ) {
$suggestions[] = 'user-profile-' . $user->type;
}
// provide the most-specific template suggestion possible for this user.
$suggestions[] = 'user-profile-' . $user->id;
}
$tpl = new Template( 'path/to/templates/folder' );
$tpl->render( $suggestions, array(
'user_name' => $user->name,
'user_bio' => $user->bio
) );
<div class="user-profile">
<h3 class="title"><?php echo $user_name; ?></h3>
<div class="content"><?php echo $user_bio; ?></div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment