How to kill execution in Twig after dump ()?

I use the {{ dump(foo) }} function in Twig to debug my templates. However, if the template causes errors after the dump () function, you will only see the Symfony debug page informing you of the error. Obviously, you can comment on breaking lines of code in a Twig template, but there is a way to kill the execution of the template immediately after the dump () function output is the last thing printed on the screen. Naively, I think of something like {{ dump(foo) }} {{ die() }} . Any ideas on how you could achieve this?

+5
source share
2 answers

You can create a simple branch extension that handled this.

Twig file ..

 namespace Acme\SomeBundle\Twig; class DevExtension extends \Twig_Extension { /** * {@inheritdoc} */ public function getFunctions() { return array( new \Twig_SimpleFunction('die', 'die'), ); } /** * {@inheritdoc} */ public function getName() { return 'acme_dev'; } } 

Your Services File (YAML) ..

 services: acme.twig.dev_extension: class: Acme\SomeBundle\Twig\DevExtension tags: - { name: twig.extension } 

Additionally, you can go to the current environment, and then either die or fail in silence, depending on the environment, if for some reason you left a stamp in your code.

Extension of your branch ..

 class DevExtension extends \Twig_Extension { /** * @string */ private $environment; /** * @param string $environment */ public function __construct($environment) { $this->environment = $environment; } /** * {@inheritdoc} */ public function getFunctions() { return array( new \Twig_SimpleFunction('die', array($this,'killRender')), ); } /** * @param string|null $message */ public function killRender($message = null) { if ('dev' === $this->environment) { die($message); } return ''; } ... } 

Your services file ..

 services: acme.twig.dev_extension: class: Acme\SomeBundle\Twig\DevExtension arguments: - %kernel.environment% tags: - { name: twig.extension } 
+10
source

I don’t think you should stop executing PHP inside your branch template (even if this is possible with the Twig user extension). The result would not be what you expect, because there is much more going on between rendering your template and sending it to the browser. If you just stop execution, all this will not happen anymore, and I suspect you will get a plain white page.

Perhaps this is the best approach to reset the variable inside the controller. This will send dump output to the web profiler toolbar, which is available even on the Symfony error page.

Oh, and fine, but how easy is it to use a comment ( {# ... #} ) to disable the non-working part of your template?

+1
source

All Articles