Skip to content

Using Twig template engine

Anatoly Nekhay edited this page Jan 7, 2019 · 1 revision

Install Twig

Learn more about Twig

composer require twig/twig

Add new dependency

Adding the following code to config/definitions.php

/**
 * Twig template engine
 *
 * @link https://twig.symfony.com/
 */
Twig_Environment::class => function($container)
{
    $loader = new Twig_Loader_Filesystem(__DIR__ . '/../templates');

    $debug = in_array($container->get('env'), ['local', 'development']);

    $twig = new Twig_Environment($loader, [
        'debug' => $debug,
        'cache' => __DIR__ . '/../cache/twig',
    ]);

    return $twig;
},

Create new directories

mkdir templates && mkdir -p cache && mkdir cache/twig

Create a template

Create the following file:

touch templates/index.html

Add the following code to the file:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Twig Example</title>
    </head>
    <body>
    <table>
        <thead>
            <tr>
                <td>Product</td>
                <td>Description</td>
                <td>Value</td>
                <td>Date</td>
            </tr>
        </thead>
        <tbody>
            {% for product in products %}
                <tr>
                    <td>{{ product.name }}</td>
                    <td>{{ product.description }}</td>
                    <td>{{ product.value }}</td>
                    <td>{{ product.date_register|date("m/d/Y") }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    </body>
</html>

Use Twig in a controller

/**
 * @Inject
 *
 * @var \Twig_Environment
 */
protected $twig;

/**
 * @param ServerRequestInterface $request
 * @param RequestHandlerInterface $handler
 *
 * @return ResponseInterface
 */
public function process(
    ServerRequestInterface $request,
    RequestHandlerInterface $handler) : ResponseInterface
{
    $products = [
        [
            'name'          => 'Notebook',
            'description'   => 'Core i7',
            'value'         =>  800.00,
            'date_register' => '2017-06-22',
        ],
        [
            'name'          => 'Mouse',
            'description'   => 'Razer',
            'value'         =>  125.00,
            'date_register' => '2017-10-25',
        ],
        [
            'name'          => 'Keyboard',
            'description'   => 'Mechanical Keyboard',
            'value'         =>  250.00,
            'date_register' => '2017-06-23',
        ],
    ];

    $content = $this->twig->render('index.html', ['products' => $products]);

    $response = $handler->handle($request);
    $response->getBody()->write($content);

    return $response;
}