Adding Twig to your SlimPHP project

After creating a basic Slim application, the next thing we did was integrate Twig so that we could start creating layouts for our application.

Once again, you can use composer to pull in the libraries you need:

composer require slim/twig-view

Once the libraries have downloaded, it’s time to integrate them with our application. Open up public/index.php and edit it so that the container now adds Twig to the container, and uses $this->view to render the response for an endpoint:

$container = new SlimContainer;
$container['settings']['displayErrorDetails'] = true;

$container['view'] = function ($container) {
    $view = new SlimViewsTwig(__DIR__.'/../views', [
        'cache' => false

    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '',     $container['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new SlimViewsTwigExtension($container['router'], $basePath));

    return $view;

$app = new SlimApp($container);
$app->get('/', function (Request $request, Response $response) {
    return $this->view->render($response, 'index.html');

The majority of this code was taken from the documentation once again, but there is one line that is of special interest:

$view = new SlimViewsTwig(DIR.’/../views’, [ ‘cache’ => false ]);

This line tells us that Twig will look in a folder called views at the same level as our public folder. Let’s create that folder and our initial view now:

mkdir views
echo "Hello World" > views/index.html

If we run the server with php -t public -S localhost:8000 once more and visit http://localhost:8000, we should see the “Hello World” message again. This is all we need to do to integrate Twig with our project.

If you wanted to pass the name is as a parameter, you can update index.php so that it passes a name variable to the view by changing your route so that it looks like the following:

$app->get('/', function (Request $request, Response $response) {
    return $this->view->render($response, 'index.html', [
        "name" => "Michael"

Then you’ll need to update views/index.html so that instead of Hello World, it says Hello {{name}}. The curly braces are Twig’s variable syntax. Refresh the page, and it should now say “Hello Michael”

One thought to “Adding Twig to your SlimPHP project”

Leave a Reply