Created
July 2, 2012 19:45
-
-
Save cam-gists/3035259 to your computer and use it in GitHub Desktop.
PHP: Template Class + usage
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 | |
//template.class.php | |
class Template | |
{ | |
protected $dir; | |
protected $vars; | |
public function __construct($dir = "") { | |
$this->dir = (substr($dir, -1) == "/") ? $dir : $dir . "/"; | |
$this->vars = array(); | |
} | |
public function __set($var, $value) { | |
$this->vars[$var] = $value; | |
} | |
public function __get($var) { | |
return $this->vars[$var]; | |
} | |
public function __isset($var) { | |
return isset($this->vars[$var]); | |
} | |
public function set() { | |
$args = func_get_args(); | |
if (func_num_args() == 2) { | |
$this->__set($args[0], $args[1]); | |
} | |
else { | |
foreach ($args[0] as $var => $value) { | |
$this->__set($var, $value); | |
} | |
} | |
} | |
public function out($template, $asString = false) { | |
ob_start(); | |
require $this->dir . $template . ".php"; | |
$content = ob_get_clean(); | |
if ($asString) { | |
return $content; | |
} | |
else { | |
echo $content; | |
} | |
} | |
} | |
?> | |
<?php | |
//template.php | |
$t = new Template(); | |
// setting a value as if it were a property | |
$t->greeting = "Hello World!"; | |
// setting a value with set() | |
$t->set("number", 42); | |
// setting multiple values with set() | |
$t->set(array( | |
"foo" => "zip", | |
"bar" => "zap" | |
)); | |
// render template | |
$t->out("mytemplate"); | |
?> | |
<!DOCTYPE html> | |
<!-- Mytemplate.php --> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
... | |
</head> | |
<body> | |
<div role="main"> | |
<h1><?=$this->greeting;?></h1> | |
... | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment