New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rendering a template from a middleware #270
Comments
I found one possible solution but I wonder if there's a better way:
|
I am also trying to use Twig in Slim 4 and I am a bit confussed. This repository seems to be oriented for those using a MVC pattern in their applications, but the base slim-skeleton creates a file structure oriented to a ADR (Action Domain Responder) pattern. In my case, I am finding more useful the solution proposed here: https://www.twilio.com/blog/adding-twig-as-a-view-renderer-to-slim-in-php. In this case, the application does not require the package Twig-View. |
I guess this defeats the purpose of the middleware approach, but to use twig-view in slim-skeleton Actions, twig must be added as a dependency, so php-di can find it: // app/dependencies.php
return function ( ContainerBuilder $containerBuilder ) {
$containerBuilder->addDefinitions( [
// ... other dependencies
\Slim\Views\Twig::class => function ( ContainerInterface $c ): \Slim\Views\Twig {
$loader = new \Twig\Loader\FilesystemLoader( '/path/to/templates' );
$settings = [
'cache' => '/path/to/cache',
// ...
];
return new \Slim\Views\Twig( $loader, $settings );
}
] );
}; Then add class ViewyAction extends Action {
private \Slim\Views\Twig $twig;
public function __construct( LoggerInterface $logger, \Slim\Views\Twig $twig ) {
parent::__construct( $logger );
$this->twig = $twig;
}
//... Then you can call protected function action(): Response {
return $this->twig->render( $this->response, 'hi.twig', [
'name' => $this->args['name']
] );
} |
I am using Twig without a container. The Readme shows examples of rendering a template from
index.php
whereTwig::fromRequest($request)
is called. However, doing this inside a middleware throws this error:Fatal error: Uncaught RuntimeException: Twig could not be found in the server request attributes using the key "view". in C:\Users\arvindpdmn\Documents\workspace\slim\vendor\slim\twig-view\src\Twig.php:74
How do I render a template from a middleware? In particular, there's one middleware that returns early when there's an error. The response will be rendered without calling the other middleware.
The text was updated successfully, but these errors were encountered: