Simple PHP templating engine with extract

<?php
 
class Template {
 
	private $_bound = array();
 
	private $_file;
 
 
    public function __construct($tplName, $tplDir = '' ) {
        // Define template directory
        if ($tplDir == '' && defined('TEMPLATE_DIR')) {
            $tplDir = TEMPLATE_DIR;
		}
 
        // Add trailing slash
        if (substr( $tplDir, strlen($tplDir) - 1, 1 ) != '/' && $tplDir != '' ) {
            $tplDir .= '/';
		}
 
        // Get templates contents
        $this->_file = $tplDir.$tplName;
    }
 
    public function set($name, $value = null) {
        // Bind associative array
        if(is_array($name)) {
			foreach ($name as $key => $value) {
				$this->_bound[$key] = $value;
            }
        } else {
			// If instance of self then save as reference
            if ($value instanceof self) {
				$this->_bound[$name] = &$value;
			} else {
				$this->_bound[$name] = $value;
			}
        }
    }
 
    public function parse() {
        // Parse templates and bind to variables
        foreach ($this->_bound as $key => $value) {
            if ($value instanceof self) {
				$value = $value->parse();
            }
 
            $$key = $value;
        }
 
        // Start outputbuffering
        ob_start();
 
        // Include template
        if (file_exists($this->_file)) {
            require($this->_file);
        } else {
            return false;
		}
 
        // Stop buffering and get its contents
        return ob_get_clean();
    }
}

Download this snippet

Simple template engine in PHP, which uses extract to set variables in the output. Example: $pTemplate = new Template('template.php'); $pTemplate->set('title', 'Here is a title'); echo $pTemplate->parse(); Contents of template.php: <title><?php echo $title;?></title>

Twitter Twitter

2 Comments to “ Simple PHP templating engine with extract”

  1. Anonymous  on Jul 13, 2010

    C3It8V <a href="http://pbvqrgclmgwc.com/">pbvqrgclmgwc</a>, [url=http://diqxaxfptnbe.com/]diqxaxfptnbe[/url], [link=http://oabmdnekumvc.com/]oabmdnekumvc[/link], http://pkeioohbibow.com/

  2. Anonymous  on Jul 31, 2010

    oHEj8L <a href="http://ewgevvfzgwxj.com/">ewgevvfzgwxj</a>, [url=http://neijiltqdckb.com/]neijiltqdckb[/url], [link=http://ggsopbryykei.com/]ggsopbryykei[/link], http://mfuxuwcetfbq.com/

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>