How to set breakpoints in Twig

Posted by ajgarlag on December 3rd 2013, at 9:30am
by Chun Xing Wong
en, php, symfony

After last PHPMad meetup, I was talking with other two group members about our daily work with the Syfmony framework and the Symfony Ecosystem. One of them told me that he loves Twig but sometimes he would like to set a breakpoint in a Twig template to debug generated code and the variables passed to the template.

Last week I had some time to investigate this and found a simple way to accomplish this creating a Twig Extension with a new breakpoint function. This new function will detect if the XDebug extension is installed and then it will the xdebug_break function to stop the debug sessión.

I've created a Composer package called ajgl/breakpoint-twig-extension that you can install with:

$ composer require ajgl/breakpoint-twig-extension

Once installed and configured, the new funcion can be called inside your twig template:

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    {{ breakpoint() }}

Remember that you must register the extension within the twig environment with

/* @var $twig Twig_Environment */
$twig->addExtension(new Ajgl\Twig\Extension\BreakpointExtension());

If you are writing a Symfony Application, you can use the provided bundle (included with the package) which will register the extension automatically:

// app/AppKernel.php
use Ajgl\Twig\Extension\SymfonyBundle\AjglBreakpointTwigExtensionBundle();

if (in_array($this->getEnvironment(), array('dev', 'test'), true)) {
    $bundles[] = new AjglBreakpointTwigExtensionBundle();

Extra tip for Netbeans users

If you are using Netbeans IDE and want to debug the PHP code generated by twig in an standard Symfony app, you must uncheck the Ignore “app/cache” Directory inside the Frameworks/Symfony2 category in the Project Properties window.

Any typo or problem? Edit this page on Github


comments powered by Disqus