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!