Last active
October 3, 2018 16:15
-
-
Save Stmol/6156350 to your computer and use it in GitHub Desktop.
Native simple PHP template engine
This file contains 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 | |
class View | |
{ | |
/** @var string Path to template */ | |
protected $_path; | |
/** @var array Variables for template */ | |
public $_var = array(); | |
public function __construct($path) | |
{ | |
$this->_path = $path; | |
} | |
/** | |
* Assign variable to template. | |
* | |
* @param string|array $name | |
* @param string $value | |
*/ | |
public function assign($name, $value) | |
{ | |
if (is_array($name)) { | |
foreach($name as $k => $v) { | |
$this->_var[$k] = $v; | |
} | |
} else { | |
$this->_var[$name] = $value; | |
} | |
} | |
/** | |
* Fetch template with params. | |
* | |
* @param string $template Name of template | |
* @param array $params Variables for template | |
* | |
* @return string Rendered template | |
*/ | |
private function fetch($template, array $params = array()) | |
{ | |
if (is_array($params) AND count($params) > 0) | |
{ | |
$this->assign($params); | |
} | |
$this->_template = $this->_path . $template; | |
if (!file_exists($this->_template)) | |
{ | |
throw new \Exception('Template not found: ' . $this->_template); | |
} else { | |
ob_start(); | |
extract($this->_var); | |
include($this->_template); | |
return ob_get_clean(); | |
} | |
} | |
/** | |
* Display template. | |
* | |
* It is a good practice to assign the variables at the end of the controller | |
* with the array as a parameter, instead of using a single method assign(). | |
* | |
* @param string $template | |
* @param array $params | |
*/ | |
public function display($template, array $params = array()) | |
{ | |
echo $this->fetch($template, $params); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment