Skip to content

Instantly share code, notes, and snippets.

@swaroopsm
Created June 21, 2014 14:24
Show Gist options
  • Save swaroopsm/0a988ef4290942818b3f to your computer and use it in GitHub Desktop.
Save swaroopsm/0a988ef4290942818b3f to your computer and use it in GitHub Desktop.
Simple implementation of PHP templating
<?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();
<!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>
<?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