Last active
January 8, 2017 04:46
-
-
Save Andrewpk/11196089 to your computer and use it in GitHub Desktop.
Simple PHP templates. Remember when PHP was a hypertext preprocessor? You don't need twig, mustache, smarty, etc., to do simple templating.
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 | |
namespace AKUtils; | |
/** | |
* A simple template class for PHP. Allows you to create templates in pure PHP. | |
* There are many template systems like it, but this one is simple. | |
*/ | |
class Template | |
{ | |
private $_templateDir=""; | |
public $properties; | |
/** | |
* set the path to your view templates | |
* @param string $_templateDir | |
*/ | |
public function setTemplatePath($_templateDir) | |
{ | |
$this->_templateDir=$_templateDir; | |
} | |
public function __construct($templateName = '') | |
{ | |
$this->properties = array(); | |
if (!empty($templateName)) { | |
$this->templateName = $templateName; | |
} | |
} | |
/** | |
* renders the template $fileName found in the template directory | |
* @param string $fileName | |
* @return mixed the output of your processed template | |
*/ | |
public function render($fileName = "") | |
{ | |
if (empty($fileName) && !empty($this->templateName)) { | |
$fileName = $this->templateName; | |
} elseif (empty($fileName) && empty($this->templateName)) { | |
return \Exception("No template provided - render cannot continue"); | |
} | |
ob_start(); | |
if (file_exists($this->_templateDir . DIRECTORY_SEPARATOR . $fileName)) { | |
include($this->_templateDir . DIRECTORY_SEPARATOR . $fileName); | |
} else { | |
if (empty($this->_templateDir)) { | |
throw new \Exception("templateDir not set and template not found"); | |
} else { | |
throw new \Exception("WAAAAA"); | |
} | |
} | |
return ob_get_clean(); | |
} | |
public function __set($k, $v) | |
{ | |
$this->properties[$k] = $v; | |
} | |
public function __get($k) | |
{ | |
return $this->properties[$k]; | |
} | |
public function __isset($k) | |
{ | |
return isset($this->properties[$k]); | |
} | |
public function __unset($k) | |
{ | |
unset($this->properties[$k]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
on line 39, it is :
} elseif ($empty($fileName) && empty($this->templateName)) {
it should be :
} elseif (empty($fileName) && empty($this->templateName)) {