How To Enable Debugging Of Twig When Used With Slim 3 Framework

4575
Share:
how-to-enable-debugging-of-twig-when-used-with-slim-3-framework

Background

When I'm developing a web application with Laravel, it has a useful helper function: dd($some_variable). It dumps the content of $some_variable into a nice and readable format. But sometimes using Laravel is overkill when the application is such a tiny to small one. Let's use this client requirement for example:

Build web application with ability to:

  1. User register, confirmation, and login. We'll need a page on admin dashboard to manage our users.
  2. Each user has ability to use our calculator by entering some values in a form. The backend will then process those values with third-party API provider A and third-party API provider B. Finally it send the final result (after applying our formula) back to user.
  3. Optionally send calculation result to user email.

Deadline would be 5 days after job awarded.

It's easy to develop this project using Laravel, but doesn't it feels like overkill? That's why I use Slim 3 for this case.

Enable Debugging on Slim 3 Framework

Mentioned on their documentation, Twig has a helper function called dump(). Detailed documentation available here: https://twig.sensiolabs.org/doc/2.x/functions/dump.html.

However, it's not enabled by default. We must add the Twig_Extension_Debug extension explicitly when creating our Twig environment:

$twig = new Twig_Environment($loader, array(
'debug' => true,
// ...
));
$twig->addExtension(new Twig_Extension_Debug());

If you're using slim-skeleton, open the file src/dependencies.php. Complete snippet would be:

// Register component on container
$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig('path/to/templates', [
        'debug' => true, // This line should enable debug mode
        'cache' => 'path/to/cache'
    ]);
    $view->addExtension(new \Slim\Views\TwigExtension(
        $container['router'],
        $container['request']->getUri()
    ));
   
    // This line should allow the use of {{ dump() }}
    $view->addExtension(new \Twig_Extension_Debug());

    return $view;
};

Detailed documentation can be found here: http://discourse.slimframework.com/t/twig-debug-mode/535/2

Tags
Share:

0 comment

Leave a reply

Your email address will not be published. Required fields are marked *