How to retrieve all Variables from a Twig Template? How to retrieve all Variables from a Twig Template? php php

How to retrieve all Variables from a Twig Template?


This is useful I find to get all the top-level keys available in the current context:

<ol>    {% for key, value in _context  %}      <li>{{ key }}</li>    {% endfor %}</ol>

Thanks to https://www.drupal.org/node/1906780


UPDATE 2019

Although {{ dump() }} does work, in some circumstances it may result in a "memory exhausted" error from PHP if it generates too much information (for example, due to recursion). In this case, try {{ dump(_context|keys) }} to get a list of the defined variables by name without dumping their contents.

UPDATE 2017

It is possible by using {{ dump() }} filter. Thanks for pointing that out in the comments!


OUTDATED

It is not possible.

You can look for these variable in twig templates and add |default('your_value') filter to them. It will check if variable is defined and is not empty, and if no - will replace it with your value.


Answer added at 2015

In the past it wasn't possible. But since version 1.5 dump() function has added. So you can get all variables from current context calling dump() without any parameters:

<pre>    {{ dump(user) }}</pre>

However, you must add the Twig_Extension_Debug extension explicitly when creating your Twig environment because dump() isn't available by default:

$twig = new Twig_Environment($loader, array(    'debug' => true,    // ...));$twig->addExtension(new Twig_Extension_Debug());

If you have been using something like Symfony, Silex, etc, dump() is available by default.

EDIT:

One can also reference all variables passed to a template (outside the context of dump()), using the global variable _context. This is what you were looking for. It is an array associating all variable names to their values.

You can find some additional info in the Twig documentation.

For this specific question however, it would probably be best to gather all of these custom variables you are speaking of, under a same umbrella variable, so that retrieving them would not be a headache. I would be an array called custom_variables or whatever.