Reputation: 476
I'm using the {{ dump(foo) }}
function in Twig to debug my templates. However, if the template is throwing errors after the dump() function, you will only see Symfony's debugging page informing you of the error. You can obviously comment out the offending lines of code in the Twig template, but is there a way to kill the execution of the template immediately after so that the output of the dump() function is the last thing printed on the screen. Naively I'm thinking of something like {{ dump(foo) }} {{ die() }}
. Any ideas on how you could achieve this?
Upvotes: 18
Views: 29158
Reputation: 17759
You could create a simple twig extension that handled this.
Your 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 could pass in the current environment and then either die or fail silently depending on the environment in case you have left the die in your code for some reason.
Your twig extension..
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 }
Upvotes: 16
Reputation: 83642
I don't think you should stop PHP execution inside your twig template (even though this is possible using a custom Twig extension). The result would not be what you'd expect because there is a lot more happening between rendering your template and sending it to the browser. If you simply stop execution all this will not happen any more and I'd suspect that you'll get a simple white page.
Perhaps it's a better approach to dump the variable inside the controller. Doing that will send the dump output to the web profiler toolbar which is available even on symfony's error page.
Oh and well, what about just using a comment ({# ... #}
) to disable the non-working part of your template?
Upvotes: 5