How to add PHP DebugBar to Twig layout?

914 views Asked by At

PHP DegugBar has an extension to display which Twig templates were rendered.

I found a demo here but if you look at how they do it, they actually render the layout in pure PHP which kind of defeats the point of Twig, which has its own layouting system.

The problem is a catch-22: I need to render the debugbar into a Twig variable so that I can put it in the Twig layout, but if I've already rendered the debugbar it won't be able to capture the fact that I'm rendering a Twig template!

So, I'm not sure how to do this. Any ideas?

3

There are 3 answers

1
Wouter J On

Create a custom Twig extension to render the code required to render the debug bar. This way, you can do {{ debug_bar() }} for instance to render the debug bar:

class DebugBarExtension extends \Twig_Extension
{
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('debug_bar', [$this, 'renderDebugBar']),
        ];
    }

    public function renderDebugBar()
    {
        // ... render and return the debug bar
    }
}
0
mpen On

\DebugBar\JavascriptRenderer::renderOnShutdownWithHead may be of use.

i.e. create a Twig function as @Wouter suggests but instead of rendering the debugbar immediately, register it to be rendered later, just before shutdown.

2
Julio Marchi On

I am not sure why do you want to render the DebugBar using Twig, unless you are trying to measure the rendering performance or something like that (which not need for the DebugBar IMO because it should never reach production anyway).

In any case, you don't need a special plugin, artifact, class or code to display the DebugBar in your Twig rendered page. You can simply do the following:

1) Add the result of the DebugBar renders (Head and Body) in the Array you are using to send variables to Twig. Example:

$template_vars['debugbar_Head'] = $debugbarRenderer->renderHead();
$template_vars['debugbar_Body'] = $debugbarRenderer->render();

2) Add the variables in your template:

<head>
  -- other stuff ---
  {{ debugbar_Head | raw }}
</head>

<body>
  {{ debugbar_Body | raw }}
  -- other stuff ---
</body>

Important: make sure your "debugbar_Head" is at the END of the head tag and the "debugbar_Body" at the beginning of the body tag (for some reason it helps prevent rare rendering errors).

3) Render your template normally:

echo $view->render('your-template-path', $template_vars);

Enjoy a Twig rendered page with a fully functional DebugBar on the bottom.

Note: there are some stuff around the web promoting some "mix" of Twig and DebugBar. Please, before try them, check if they are not framework related.