webiik/view

The View provides common interface for rendering templates, no matter what template engine you want to use. Out of the box it supports Twig.

1.2 2020-06-08 16:45 UTC

This package is auto-updated.

Last update: 2024-11-09 02:48:42 UTC


README

View

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.

Installation

composer require webiik/view

Example

$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']);

Configuration

setRenderer

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.

Rendering

render

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']);

Other

getTemplateEngine

getTemplateEngine()

getTemplateEngine() gets object of template engine using by renderer.

$view->getTemplateEngine(); // e.g. returns Twig_Environment

Resources