Templates (Twig)
Slim is built around routing and APIs, so it has no templating engine of its own. If every route in your app returns JSON (see Building JSON APIs), you don't need one. But when Slim is used to render actual HTML pages, mixing raw HTML strings into your route closures gets messy fast — that's where Twig comes in.
Installing Twig View
The Slim team maintains an official integration package, slim/twig-view, that wires
Twig into Slim's response objects. Install it with Composer, the same way Slim itself was installed
(see Installation & Setup):
composer require slim/twig-view
Registering Twig in the Container
Point Twig at a folder of template files, then register it in the DI container so route handlers can retrieve it:
<?php
require __DIR__ . '/../vendor/autoload.php';
use DI\Container;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
$container = new Container();
AppFactory::setContainer($container);
$container->set('view', function () {
return Twig::create(__DIR__ . '/../templates', ['cache' => false]);
});
$app = AppFactory::create();
Setting 'cache' => false is fine for development; in production you'd point it at a writable cache folder so Twig doesn't recompile templates on every request.
Rendering a Template from a Route
Pull the view out of the container and call render(), passing the template file name and an array of variables it should have access to:
<?php
$app->get('/hello', function ($request, $response) {
$view = $this->get('view');
return $view->render($response, 'home.twig', ['name' => 'Sonu']);
});
The Twig Template File
The corresponding templates/home.twig file is plain HTML with Twig's {{ }} syntax dropped in wherever a PHP variable needs to appear:
<!doctype html>
<html>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
When the route above runs, {{ name }} is replaced with the value of 'name'
from the array passed to render() — here, Hello, Sonu!
json_encode()'d data as you have been. Twig only matters once Slim starts rendering full HTML pages for a browser to display.