Last active
February 18, 2018 22:18
-
-
Save mulhoon/0fdf074223353c1752d9 to your computer and use it in GitHub Desktop.
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 | |
/* | |
Original by Rasmus Larsson | |
http://www.rasmuslarsson.se/2013/05/a-template-engine-in-php/ | |
*/ | |
class Template | |
{ | |
protected $template; | |
protected $variables = array(); | |
public function __construct($template) | |
{ | |
$this->template = $template; | |
} | |
public function __get($key) | |
{ | |
return $this->variables[$key]; | |
} | |
public function __set($key, $value) | |
{ | |
$this->variables[$key] = $value; | |
} | |
public function __toString() | |
{ | |
extract($this->variables); | |
chdir(dirname($this->template)); | |
ob_start(); | |
include basename($this->template); | |
return ob_get_clean(); | |
} | |
} | |
/* Usage: | |
require 'templateEngine.php'; | |
$message = new Template("templates/template1.html"); | |
$message->username = $username; | |
echo $message; | |
// in your template use... | |
<?= $username ?> | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment