Skip to content

Instantly share code, notes, and snippets.

@oranj
Created February 16, 2012 05:42
Show Gist options
  • Save oranj/1842400 to your computer and use it in GitHub Desktop.
Save oranj/1842400 to your computer and use it in GitHub Desktop.
Templating system for upcoming CMS-
<?php
class CN_Page {
private $page_regions = Array();
private $page_region_data = Array();
private $page_region_count = Array();
const dynamic_key = 'dynamic';
const html_key = 'html';
const placeholder = '[[%s]]';
const region_comment_bof = '<!-- BOF %s -->';
const region_comment_eof = '<!-- EOF %s -->';
const regex = '/\(\[region\:([^\]]+)\]\)/i';
public function __construct($filename) {
$this->load_file($filename);
}
public function load_file($filename) {
$fullpath = CFG("dir", "templates").$filename;
if (! file_exists($fullpath)) {
throw new Exception("Template <strong>$fullpath</strong> does not exist");
}
$this->parse_template(file_get_contents($fullpath));
}
public function get_page() {
$html = '';
foreach ($this->page_regions as $region) {
list($type, $info) = $region;
switch($type) {
case self::dynamic_key:
if (isset($this->page_region_data[$info])) {
$html .= sprintf(self::region_comment_bof, $info).$this->page_region_data[$info].sprintf(self::region_comment_eof, $info);
} else {
$html .= sprintf(self::placeholder, $info);
}
break;
case self::html_key:
$html .= $info;
break;
}
}
return $html;
}
public function set_region($key, $html) {
$this->page_region_data[$key] = $html;
}
private function add_region_dynamic($key) {
if (! isset($this->page_region_count[$key])) {
$this->page_region_count[$key] = 1;
} else {
$this->page_region_count[$key]++;
}
$this->page_regions[]= Array(self::dynamic_key, $key);
}
private function add_region_html($text) {
$this->page_regions[]= Array(self::html_key, $text);
}
private function parse_template($in_html) {
if (preg_match_all(self::regex, $in_html, $matches, PREG_OFFSET_CAPTURE)) {
$previous_end = 0;
foreach ($matches[0] as $index => $match) {
if ($previous_end != $match[1]) {
$this->add_region_html(substr($in_html, $previous_end, $match[1] - $previous_end));
}
$this->add_region_dynamic($matches[1][$index][0]);
$previous_end = $match[1] + strlen($match[0]);
}
if ($previous_end != $match[1]) {
$this->add_region_html(substr($in_html, $previous_end));
}
} else {
$this->add_region_html($in_html);
}
}
}
<!DOCTYPE html>
<html>
<head>
([region:head])
</head>
<body>
([region:header])
([region:left])
([region:right])
([region:content_title])
([region:content])
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment