Skip to content

Instantly share code, notes, and snippets.

@Andrewpk
Last active January 8, 2017 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrewpk/11196089 to your computer and use it in GitHub Desktop.
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.
<?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]);
}
}
@bantya
Copy link

bantya commented Aug 24, 2016

on line 39, it is :
} elseif ($empty($fileName) && empty($this->templateName)) {
it should be :
} elseif (empty($fileName) && empty($this->templateName)) {

@Andrewpk
Copy link
Author

Andrewpk commented Jan 8, 2017

Thanks @bantya, great catch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment