The View provides common interface for rendering templates, no matter what template engine you want to use. Out of the box it supports Twig template engine.
composer require webiik/view
$view = new \Webiik\View\View();
// Prepare Twig renderer factory
$renderer = function() {
// Instantiate Twig template engine
$loader = new Twig_Loader_Filesystem(__DIR__ . '/view');
$environment = new Twig_Environment($loader, array(
'cache' => __DIR__ . '/tmp/view'
));
// Instantiate and return Twig renderer
return new \Webiik\View\Renderer\Twig($environment);
};
// Add renderer
$view->setRenderer($renderer);
// Render template
echo $view->render('test.twig', ['foo' => 'meow']);
setRenderer(callable $factory):void
setRenderer() adds a renderer - a factory of implementation of RendererInterface on template engine.
$view->setRenderer($renderer);
Write Custom Renderer
You can write your custom renderer. The only thing you have to do is to implement RendererInterface. Look at the implementation of RendererInterface on Twig template engine and get better insight.
render(string $template, array $data = []): string
render() renders template to string.
Parameters
- template name of template to render
- data array of data to pass to template
echo $view->render('test.twig', ['foo' => 'meow']);
getTemplateEngine()
getTemplateEngine() gets object of template engine using by renderer.
$view->getTemplateEngine(); // e.g. returns Twig_Environment