Render twig from CustomErrorRenderer

How do I replace ‘My awesome format’ in the sample below (from the docs) with the twig->render? How can I bring container in? I’m trying to render custom error pages in my app using twig

<?php
use Slim\Interfaces\ErrorRendererInterface;
use Throwable;

class MyCustomErrorRenderer implements ErrorRendererInterface
{
    public function __invoke(Throwable $exception, bool $displayErrorDetails): string
    {
        return 'My awesome format';
    }
}

You can always declare that within the constructor (dependency injection).

Example:

<?php

use Psr\Http\Message\ResponseFactoryInterface;
use Slim\Interfaces\ErrorRendererInterface;
use Slim\Views\Twig;
use Throwable;

class MyCustomErrorRenderer implements ErrorRendererInterface
{
    private Twig $twig;
    private ResponseFactoryInterface $responseFactory;

    public function __construct(Twig $twig, ResponseFactoryInterface $responseFactory)
    {
        $this->twig = $twig;
        $this->responseFactory = $responseFactory;
    }

    public function __invoke(Throwable $exception, bool $displayErrorDetails): string
    {
        $viewData = [
            'error' => [
                'message' => 'Test error',
            ],
        ];

        $response = $this->responseFactory->createResponse();

        $result = (string)$this->twig->render($response, 'test.twig', $viewData)->getBody();

        return $result;
    }
}

1 Like

Thank you, that worked!

Hello and thanks for this example, I got to the stage of MyCustomErrorRenderer to display “my awesome format” (under SLIM 4), but trying to use twig in the above code example, the class construct complains (fatal error) __construct(): Argument #1 ($twig) must be of type Slim\Views\Twig, null given. It doesn’t seem to be able to create an instance of Twig inside the class. Do you have any ideas on how to do this under Slim 4 ? Or it might be something else?… Thanks!