This repository has been archived on 2024-06-26. You can view files and clone it, but cannot push or open issues or pull requests.
sakura/libraries/Template.php

89 lines
2.2 KiB
PHP
Raw Normal View History

2015-10-30 16:15:58 +00:00
<?php
/*
2015-10-31 18:14:54 +00:00
* Template engine wrapper
2015-10-30 16:15:58 +00:00
*/
namespace Sakura;
2015-10-31 18:14:54 +00:00
use Twig_Environment;
use Twig_Extension_StringLoader;
use Twig_Loader_Filesystem;
2015-10-30 16:15:58 +00:00
/**
* Class Template
* @package Sakura
*/
class Template
{
2015-10-31 18:14:54 +00:00
// Engine container, template folder name, options and template variables
private $vars = [];
private $template;
private $templateName;
private $templateOptions;
// Initialise templating engine and data
2015-11-01 13:26:05 +00:00
public function __construct()
2015-10-31 18:14:54 +00:00
{
// Set template to default
2015-12-04 14:19:10 +00:00
$this->setTemplate(Config::get('site_style'));
2015-10-31 18:14:54 +00:00
}
// Set a template name
2015-11-01 13:26:05 +00:00
public function setTemplate($name)
{
2015-10-31 18:14:54 +00:00
// Assign config path to a variable so we don't have to type it out twice
$confPath = ROOT . 'templates/' . $name . '/template.ini';
2015-10-31 18:14:54 +00:00
// Check if the configuration file exists
if (!file_exists($confPath)) {
trigger_error('Template configuration does not exist', E_USER_ERROR);
}
// Parse and store the configuration
$this->templateOptions = parse_ini_file($confPath, true);
// Set variables
$this->templateName = $name;
// Reinitialise
$this->initTemplate();
}
// Initialise main template engine
2015-11-01 13:26:05 +00:00
public function initTemplate()
{
2015-10-31 18:14:54 +00:00
// Initialise Twig Filesystem Loader
$twigLoader = new Twig_Loader_Filesystem(ROOT . 'templates/' . $this->templateName);
2015-10-31 18:14:54 +00:00
// Environment variable
$twigEnv = [];
// Enable caching
2015-12-04 14:19:10 +00:00
if (Config::get('enable_tpl_cache')) {
2015-12-01 13:34:16 +00:00
$twigEnv['cache'] = ROOT . 'cache/twig';
2015-10-31 18:14:54 +00:00
}
// And now actually initialise the templating engine
$this->template = new Twig_Environment($twigLoader, $twigEnv);
// Load String template loader
$this->template->addExtension(new Twig_Extension_StringLoader());
}
// Set variables
2015-11-01 13:26:05 +00:00
public function setVariables($vars)
{
2015-10-31 18:14:54 +00:00
$this->vars = array_merge($this->vars, $vars);
}
// Render a template
public function render($file)
{
try {
return $this->template->render($file, $this->vars);
} catch (\Exception $e) {
trigger_error($e->getMessage(), E_USER_ERROR);
2015-10-31 18:14:54 +00:00
}
}
2015-10-30 16:15:58 +00:00
}