Skip to content

Instantly share code, notes, and snippets.

@aNNiMON
Last active August 29, 2015 14:26
Show Gist options
  • Save aNNiMON/263877094a075c3a5ce5 to your computer and use it in GitHub Desktop.
Save aNNiMON/263877094a075c3a5ce5 to your computer and use it in GitHub Desktop.
<?php
/**
* Simple template engine
*/
class Template {
private static $templatesPath = 'templates/';
private static $cache = array();
/**
* @param string $name filename without extension
* @return self
*/
public static function from($name) {
return self::fromPath(self::$templatesPath, $name);
}
/**
* @param string $path path to directory of template files
* @param string $name filename without extension
* @return self
*/
public static function fromPath($path, $name) {
return new Template($path, $name);
}
/**
* Merge templates to one string
* @param Template[] $templates
* @param string $separator
* @return string
*/
public static function merge(array $templates, $separator = "\n") {
$output = '';
foreach ($templates as $template) {
$output .= $template->render() . $separator;
}
return $output;
}
/**
* @param string $templatesPath
*/
public static function setTemplatesPath($templatesPath) {
self::$templatesPath = $templatesPath;
}
/**
* @return string
*/
public static function getTemplatesPath() {
return self::$templatesPath;
}
protected $file;
protected $values;
protected $excludeFromCache;
private function __construct($templatesPath, $file) {
$this->file = $templatesPath . $file . '.tpl';
$this->values = array();
$this->excludeFromCache = false;
}
/**
* Add data to view
* @param string|array $key
* @param mixed $value
* @return $this
*/
public function with($key, $value) {
if (is_array($key)) {
$this->values = array_merge($this->values, $key);
} else {
$this->values[$key] = $value;
}
return $this;
}
public function excludeFromCache() {
$this->excludeFromCache = true;
return $this;
}
/**
* Render template
* @return string
*/
public function render() {
// Get template content from storage or cache
if (array_key_exists($this->file, self::$cache)) {
$output = self::$cache[$this->file];
} else {
$output = file_get_contents($this->file);
if (!$this->excludeFromCache) {
self::$cache[$this->file] = $output;
}
}
// {|key|} - multilanguage key
$output = preg_replace_callback('#\{\|(.*?)\|\}#u', function($key) {
global $lang;
return $lang->get($key[1]);
}, $output);
// {?key?} - if key doesn't exists - clear value
$output = preg_replace_callback('#\{\?(.*?)\?\}#u', function($key) {
if (array_key_exists($key[1], $this->values)) {
return $this->values[$key[1]];
}
return '';
}, $output);
// {key} - normal replace if exists
foreach ($this->values as $key => $value) {
$output = str_replace('{'.$key.'}', $value, $output);
}
return $output;
}
public function __toString() {
return $this->render();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment