Is it possible to retrieve all variables inside a Twig template with PHP?
Example someTemplate.twig.php:
Hello {{ name }},
your new email is {{ ema
Here is the best way and easiest way to dump all variables :
{{ dump () }}
Source : https://www.drupal.org/docs/8/theming/twig/discovering-and-inspecting-variables-in-twig-templates
You have to parse the template, and walk through the AST it returns:
$loaded = $twig->getLoader()->getSource($template);
var_dump(extractVars($twig->parse($twig->tokenize($loaded))));
function extractVars($node)
{
if (!$node instanceof Traversable) return array();
$vars = array();
foreach ($node as $cur)
{
if (get_class($cur) != 'Twig_Node_Expression_Name')
{
$vars = array_merge($vars, call_user_func(__FUNCTION__, $cur));
}
else if ($cur->getAttribute('always_defined') == false)
{
// List only predefined variables expected by template,
// filtering out `v` and leaving `arr` from `{% for v in arr%}`
$vars[] = $cur->getAttribute('name');
}
}
return $vars;
}