Dynadot

PHP5 Template Class

Spaceship Spaceship
Watch
Impact
5,506
Hello again,

This is a very lightweight and very easy to use template class for PHP5. Supports sub templates using a nice little magical method. ;)

Template Class

PHP:
<?php
/**
 * Basic template engine for PHP5. Not bloated
 * and just gets the job done.
 *
 * @package Template
 * @author David Parr <[email protected]>
 * @copyright Copyright (c) David Parr, 2008
 */
 
class Template
{
    // Template name
    protected $name;
    
    // Local and global data. Gl
    protected $data = array();
    
    /**
     * Constructor sets the template name, and makes sure
     * it exists.
     *
     * @param string The template name
     */
    public function __construct($name)
    {
        if( ! is_file(TEMPLATE_PATH . $name . TEMPLATE_EXT))
            die('Invalid template: ' . $name);
            
        $this->name = $name;
    }
    
    /**
     * Magically set some template data.
     *
     * @param string Key of the data
     * @param string Value of the data
     */
    public function __set($key, $value)
    {
        $this->data[$key] = $value;
    }
    
    /**
     * Magically render a template. Great for sub templates.
     *
     * @return string
     */
    public function __toString()
    {
        // Need the new line character to format output correctly :)
        return $this->render() . "\n";
    }
    
    /**
     * Renders a template.
     *
     * @param bool Should the template be directly printed out?
     * @return string
     */
    public function render($print = FALSE)
    {
        // Begin output buffering
        ob_start();
        
        // Extract data to local namespace. Don't worry extract isn't great
        // but this is only in local scope so nothing to worry about :)
        extract($this->data, EXTR_SKIP);
        
        // We do it like this so we can use the direct name of the variable
        // rather than having $this everywhere in your templates
        require_once(TEMPLATE_PATH . $this->name . TEMPLATE_EXT);
        
        $output = ob_get_clean();
        
        if($print === TRUE)
        {
            echo $output;
            return true;
        }
        
        return $output;
    }
}
?>

Example

PHP:
<?php
require_once('classes/Template.php');

// Template path with a trailing slash and extension of template files with a dot prefix.
// This lets you decide where to place your templates and what extension to give them i.e. '.template.php', '.tpl.php'
// or whatever suits your needs.
define('TEMPLATE_PATH', dirname(__FILE__) . '/templates/');
define('TEMPLATE_EXT', '.php');

// Create a home template, with header and footer as sub templates
$home = new Template('home');
$home->message = 'Hello world';

$home->header = new Template('header');

// This is how you set a variable in a sub template. Easy as pie :)
$home->header->title = 'Home Page';

$home->footer = new Template('footer');

$home->render(TRUE);

?>

Header

PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title><?php echo $title; ?></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>

Home

PHP:
<?php echo $header; ?>
    <h1><?php echo $message; ?></h1>
<?php echo $footer; ?>

Footer

PHP:
</body>
</html>

All the above will produce..

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
    <h1>Hello world</h1>
</body>
</html>

Thanks and enjoy!
:wave:
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
What am I missing?

Why is it the $home->header-title doesn't show up as I would expect?

Even in your example output above the $title is not set - is that intentionally or am I missing something very basic here?

Thanks!
 
0
•••
Elegant example!

The next step could be to create your own template language and eliminate that PHP from the templates altogether..

Code:
<html>
<head>
<title>##$title##</title>
</head>
<body>
##if $name##
Hello ##$name##, welcome to ##$sitename##!
##/if##
</body>

But really this is a good job and hopefully I will use it.
 
0
•••
I'm having the same issue with the "title" variable. Any ideas why this is happening?
 
0
•••
Update

Ok guys give this update a try. Should work fine now. :bingo:

PHP:
  <?php
/**
* Basic template engine for PHP5. Not bloated
* and just gets the job done.
*
* @package Template
* @author David Parr <[email protected]>
* @copyright Copyright (c) David Parr, 2008
* @version 07/12/2007
*/

class Template
{
    // Template name
    protected $name;
    
    // Local and global data. Gl
    protected $data = array();
    
    /**
     * Constructor sets the template name, and makes sure
     * it exists.
     *
     * @param string The template name
     */
    public function __construct($name)
    {
        if( ! is_file(TEMPLATE_PATH . $name . TEMPLATE_EXT))
            die('Invalid template: ' . $name);
            
        $this->name = $name;
    }
    
    /**
     * Magically set some template data.
     *
     * @param string Key of the data
     * @param string Value of the data
     */
    public function __set($key, $value)
    {
        $this->data[$key] = $value;
    }

    /**
     * Magically gets a template variable.
     *
     * @param string $key
     * @return mixed
     */
    public function __get($key)
    {
       return $this->data[$key];
    }
    
    /**
     * Magically render a template. Great for sub templates.
     *
     * @return string
     */
    public function __toString()
    {
        // Need the new line character to format output correctly :)
        return $this->render() . "\n";
    }
    
    /**
     * Renders a template.
     *
     * @param bool Should the template be directly printed out?
     * @return string
     */
    public function render($print = FALSE)
    {
        // Begin output buffering
        ob_start();
        
        // Extract data to local namespace. Don't worry extract isn't great
        // but this is only in local scope so nothing to worry about :)
        extract($this->data, EXTR_SKIP);
        
        // We do it like this so we can use the direct name of the variable
        // rather than having $this everywhere in your templates
        require_once(TEMPLATE_PATH . $this->name . TEMPLATE_EXT);
        
        $output = ob_get_clean();
        
        if($print === TRUE)
        {
            echo $output;
            return true;
        }
        
        return $output;
    }
}
?>

Thanks!
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back