Created
June 21, 2014 14:24
-
-
Save swaroopsm/0a988ef4290942818b3f to your computer and use it in GitHub Desktop.
Simple implementation of PHP templating
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 | |
require 'templateengine.php'; | |
$name = 'Swaroop'; | |
$age = 24; | |
$template = new TemplateEngine(); | |
$template->setTemplate('template.php'); | |
$template->setData('name', $name); | |
$template->setData('age', $age); | |
$template->render(); |
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title></title> | |
</head> | |
<body> | |
I am <?= $name ?>. | |
<p>I am <?= $age ?> old.</p> | |
</body> | |
</html> |
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 | |
class TemplateEngine { | |
private $template; | |
private $data; | |
public function __construct() { | |
$this->data = array(); | |
} | |
public function setTemplate($file) { | |
$this->template = $file; | |
} | |
public function setData($name, $value) { | |
$this->data[$name] = $value; | |
} | |
public function render() { | |
ob_start(); | |
foreach($this->data as $key => $value) { | |
${$key} = $value; | |
} | |
require $this->template; | |
$contents = ob_get_contents(); | |
ob_end_clean(); | |
echo $contents; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment