View layer pattern where you only present what you have been given is fine and all, but how do you know what is available? Is there a \"list all defined variables\" function
For debugging Twig templates you can use the debug statement.
There you can set the debug setting explicitely.
The complete recipe here for quicker reference (note that all the steps are mandatory):
1) when instantiating Twig, pass the debug option
$twig = new Twig_Environment(
$loader, ['debug'=>true, 'cache'=>false, /*other options */]
);
2) add the debug extension
$twig->addExtension(new \Twig_Extension_Debug());
3) Use it like @Hazarapet Tunanyan pointed out
{{ dump(MyVar) }}
or
{{ dump() }}
or
{{ dump(MyObject.MyPropertyName) }}
As most good PHP programmers like to use XDebug to actually step through running code and watch variables change in real-time, using dump()
feels like a step back to the bad old days.
That's why I made a Twig Debug extension and put it on Github.
https://github.com/delboy1978uk/twig-debug
composer require delboy1978uk/twig-debug
Then add the extension. If you aren't using Symfony, like this:
<?php
use Del\Twig\DebugExtension;
/** @var $twig Twig_Environment */
$twig->addExtension(new DebugExtension());
If you are, like this in your services YAML config:
twig_debugger:
class: Del\Twig\DebugExtension
tags:
- { name: twig.extension }
Once registered, you can now do this anywhere in a twig template:
{{ breakpoint() }}
Now, you can use XDebug, execution will pause, and you can see all the properties of both the Context and the Environment.
Have fun! :-D
So I got it working, partly a bit hackish:
twig: debug: 1
in app/config/config.yml
Add this to config_dev.yml
services:
debug.twig.extension:
class: Twig_Extensions_Extension_Debug
tags: [{ name: 'twig.extension' }]
sudo rm -fr app/cache/dev
print_r()
, I opened vendor/twig-extensions/lib/Twig/Extensions/Node/Debug.php
and changed print_r(
to d(
PS. I would still like to know how/where to grab the $twig environment to add filters and extensions.
If you are using Twig in your application as a component you can do this:
$twig = new Twig_Environment($loader, array(
'autoescape' => false
));
$twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));
Then in your templates:
{{ my_variable | var_dump }}
Dump all custom variables:
<h1>Variables passed to the view:</h1>
{% for key, value in _context %}
{% if key starts with '_' %}
{% else %}
<pre style="background: #eee">{{ key }}</pre>
{{ dump(value) }}
{% endif %}
{% endfor %}
You can use my plugin which will do that for you (an will nicely format the output):
Twig Dump Bar