Warning: Undefined array key "Cookie" in /home/webap/logdb.net/app/App.php on line 35

Warning: Trying to access array offset on null in /home/webap/logdb.net/app/App.php on line 35
Twig Templates - Slim Framework

Twig Templates

The slim/twig-view component

The Twig-View PHP component helps you render Twig templates in your application. This component is available on Packagist, and it’s easy to install with Composer like this:

Installation

composer require slim/twig-view

Usage

Next, you need to add the middleware to the Slim app:

Note: For production scenarios, cache should be set to some 'path/to/cache' to store compiled templates (thus avoiding recompilation on every request). For more information, see Twig environment options

$app->get('/', function ($request, $response) {
    $view = Twig::fromRequest($request);
    
    return $view->render($response, 'home.html.twig', [
        'name' => 'John',
    ]);
});

// Run app
$app->run();

In this example, $view invoked inside the route callback is a reference to the \Slim\Views\Twig instance returned by the fromRequest method. The \Slim\Views\Twig instance’s render() method accepts a PSR-7 Response object as its first argument, the Twig template path as its second argument, and an array of template variables as its final argument. The render() method returns a new PSR-7 Response object whose body is the rendered Twig template.

Create a directory in your project root: templates/

Create a Twig template file within the templates directory: templates/home.html.twig


<!DOCTYPE html>
<html>
<head>
<title>Welcome to Slim!</title>
</head>
<body>
<h1>Hello test</h1>
</body>
</html>

            

Read more