Skip to content

Instantly share code, notes, and snippets.

@pthrasher
Created February 2, 2012 17:23
Show Gist options
  • Save pthrasher/1724678 to your computer and use it in GitHub Desktop.
Save pthrasher/1724678 to your computer and use it in GitHub Desktop.
A very very simple templating class for php... seriously... probably has too few features.
<?php
class Simplate {
/*
* Sets include file name, and sanitizes vars.
*/
function __contruct($template_name = '404', $vars = array()) {
// Escapt all values by default.
$this->template_vars = $this->sanitize_vars($vars);
// Todo... ensure we don't allow paths here... only filenames.
$this->template_include = $template_name . '.tpl.php';
}
/*
* Sanitizes vars. Keeps old values and prepends them with unsafe_
*/
private function sanitize_vars($vars) {
$tmp = array();
foreach ($vars as $key => $value) {
$tmp[$key] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
$tmp["unsafe_" . $key] = $value;
}
}
/*
* Renders the template to a buffer, and returns the output.
*/
function render() {
$vars = $this->template_vars;
$template = $this->template_include;
extract($vars);
// Clean the scope.
unset($this);
unset($vars);
ob_start();
include($template);
$page = ob_get_contents();
ob_end_flush();
return $page;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment