<?php
use DI\Container;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
require __DIR__ . '/../vendor/autoload.php';
$container = new Container();
AppFactory::setContainer($container);
// Set view in Container
$container->set('view', function () {
return Twig::create(__DIR__ . '/../templates', ['cache' => false]);
});
$app = AppFactory::create();
$app->add(TwigMiddleware::createFromContainer($app));
$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware();
$app->addErrorMiddleware(true, true, true);
$app->get('/', function (Request $request, Response $response) {
$view = Twig::fromRequest($request); // throws RuntimeException here
$response->getBody()->write($view->fetchFromString('Current_url: {{ current_url() }}'));
return $response;
});
$app->run();
Result: Uncaught RuntimeException: Twig could not be found in the server request attributes using the key "view"
Slim Application Error
The application could not run because of the following error:
Details
Type: RuntimeException
Code: 0
Message: Twig could not be found in the server request attributes using the key "view".
File: vendor/slim/twig-view/src/Twig.php
Line: 74
$app->add(TwigMiddleware::create($app, $container->get('view')));
// or
$app->add(TwigMiddleware::create($app, $container->get(Twig:class)));
// or manually
$app->add(
new TwigMiddleware(
$container->get('view'),
$app->getRouteCollector()->getRouteParser(),
$app->getBasePath(),
'view' // <<<<---- see here
)
);
The static method
TwigMiddleware::createFromContainer()
does not pass the$attributeName
parameter to the constructor.https://github.com/slimphp/Twig-View/blob/3.x/src/TwigMiddleware.php#L56-L60
Example application
Result:
Uncaught RuntimeException: Twig could not be found in the server request attributes using the key "view"
https://github.com/slimphp/Twig-View/blob/3.x/src/Twig.php#L73-L77
Expected result: No error
Workaround: Use the
create
method instead: