/** * Process a template (catch displayed content) * * @param string $id template id * @param array $vars template variables * * @return string parsed template content */ public static function process($id, $vars = array()) { // Are we asked to not output context related html comments ? $addctx = true; if (substr($id, 0, 1) == '!') { $addctx = false; $id = substr($id, 1); } // Resolve template file path $path = self::resolve($id); return (new Event('template_process', $id, $path, $vars, $addctx))->trigger(function ($id, $path, $vars, $addctx) { // Lambda renderer to isolate context $renderer = function ($_path, $_vars) { foreach ($_vars as $_k => $_v) { if (substr($_k, 0, 1) != '_') { ${$_k} = $_v; } } include $_path; }; // Render $exception = null; ob_start(); try { $renderer($path, $vars); } catch (Exception $e) { $exception = $e; } $content = ob_get_clean(); // Translation syntax $content = preg_replace_callback('`\\{(loc|tr|translate):([^}]+)\\}`', function ($m) { return (string) Lang::translate($m[2]); }, $content); // Config syntax $content = preg_replace_callback('`\\{(cfg|conf|config):([^}]+)\\}`', function ($m) { return Config::get($m[2]); }, $content); // Image syntax $content = preg_replace_callback('`\\{(img|image):([^}]+)\\}`', function ($m) { return GUI::path('images/' . $m[2]); }, $content); // Path syntax $content = preg_replace_callback('`\\{(path):([^}]*)\\}`', function ($m) { return GUI::path($m[2]); }, $content); // URL syntax $content = preg_replace_callback('`\\{(url):([^}]*)\\}`', function ($m) { return preg_replace('`^(https?://)?([^/]+)/`', '/', Config::get('application_url')) . $m[2]; }, $content); // Add context as a html comment if required if ($addctx) { $content = "\n" . '<!-- template:' . $id . ' start -->' . "\n" . $content . "\n" . '<!-- template:' . $id . ' end -->' . "\n"; } // If rendering threw rethrow if ($exception) { throw $exception; } return $content; }); }
/** * Compute base path * * @param mixed $location location to append * * @return string */ public static function path($location = null) { if (is_null(self::$path)) { self::$path = preg_replace('`^(https?://)?([^/]+)/`', '/', Config::get('application_url')); } if (is_array($location)) { return array_map(function ($l) { return GUI::path($l); }, $location); } if ($location && substr($location, -1) != '/' && substr($location, 0, 1) != '?') { $location .= (strpos($location, '?') ? '&' : '?') . 'v=' . Utilities::runningInstanceUID(); } return self::$path . $location; }