PHP Twig Template Wrapper
Requirements
- Twig downloaded and unarchived
- Twig Autoloader registered
Template Class
The use of the Settings class is self explanatory. Just replaces the instances of Settings with your own configuration system (or just strings). All Twig settings are documented here.
class Template
{
public $context = array();
private $template;
public function __construct($template)
{
$loader = new Twig_Loader_Filesystem(Settings::get('template_directories'));
$twig = new Twig_Environment($loader, array(
'cache' => Settings::get('template_cache_directory'),
'debug' => Settings::get('debug'),
)
);
$this->template = $twig->loadTemplate($template);
}
public function setContext(array $context = array())
{
$this->context = array_merge($context, $this->context);
}
public function render()
{
return $this->template->render($this->context);
}
public function __toString()
{
return $this->render();
}
public function __set($key, $val)
{
$this->context[$key] = $val;
}
public function __get($key)
{
return $this->context[$key];
}
}
Simple Example
hello.html
Hey there <strong>{{ name }}</strong> welcome to the website.
Code in controller
$t = new Template('hello.html');
$t->name = 'Frank';
echo $t->render();
Output:
Hey there <strong>Frank</strong> welcome to the website.
Example with Inheritance
base.html
<h3>Welcome to the website<h3>
{% block content %}{% endblock %}
hello.html
{% extends 'base.html' %}
{% block content %}
Hey there <strong>{{ name }}</strong> welcome to the website.
{% endblock %}
Code in controller
$t = new Template('hello.html');
$t->name = 'Joe';
echo $t->render();
Output:…



