简体   繁体   中英

How to add PHP DebugBar to Twig layout?

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?

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
    }
}

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM