Use Twig with Slim Framework


Install Slim Framework with composer:

composer require slim/slim

Install Twig:

composer require twig/twig

And finally, install Twig view for Slim Framework:

composer require slim/twig-view

Open your PHP code and create Slim application:

$app = new \Slim\App(new \Slim\Container);

Get the container, create and configure Twig:

require_once 'vendor/autoload.php';

# ...

$container = $app->getContainer();

$container['view'] = function($container)
    $view = new \Slim\Views\Twig('/path/to/website/templates');
    $twig = $view->getEnvironment();
    $twig->addGlobal('greetings', 'Hello');

    $twig->addFunction(new Twig_SimpleFunction('plus', function($a, $b)
        return $a + $b;

    # Do the rest of the initialization

    return $view;

Register the request handler and render a template:

$app->get('/', function($request, $response)
    return $this->view->render($response, 'index.html');

# ...


And finally, create index.html:

<!DOCTYPE html>
<html lang="en">
        <title>{{ greetings }}</title>
        Two plus three equals {{ plus(2 + 3) }}
Rate this post:
Share this page:

See also how to:

How to make POST and other types of HTTP requests and add custom HTTP headers with file_get_contents function in PHP
How to run your PHP or Bash script as root in the most secure way
How to use modern MaxMind GeoIP API in PHP
How to split YAML files and include them into each other with PHP
How to protect your website forms from unwanted spam bots