Discovering and Inspecting Variables in Twig Templates
This documentation needs review. See "Help improve this page" in the sidebar.
When working with a Twig template file most variables are documented in the comments for the template file. However, when they are not, or when themes or modules introduce new variables we need a way to discover all the variables available within the scope of a template. Twig provides the dump()
function for discovering and inspecting variables in template files.
The dump()
function will not display any output unless debugging is enabled. Learn how to enable Twig debugging.
Once enabled, the dump()
function can be used to output information about a variable or variables within a template.
Inspecting a single variable
If your template has a title
variable available, the following will dump its contents to your template:
{{ dump(title) }}
Discovering all available variables in a template
To dump all available variables and their contents in a template, add the following to your template (after enabling debugging):
{{ dump() }}
To dump only the available variable keys use:
{{ dump(_context|keys) }}
There are additional global variables available in all Twig templates:
_self
references the current template and contains advanced information about a template, i.e. the compiled template class name and information about the Twig environment. _self was deprecated and removed from Twig version 2.x._context
references the current context and contains all variables passed to the template such as variables sent from theme(), prepared by preprocess, or set in the template. Adding{{ dump() }}
without specifying a variable is equivalent to{{ dump(_context) }}
._charset
references the current character set.
These techniques will only dump keys for non-computed values. For example, you might have an ID at node.field_main_image.target_id
. You can access the entity at node.field_main_image.entity
, but the entity
key will not appear in lists of keys because it is a computed value.
Beware of dump()
(prior to Drupal 9.5)
Prior to Drupal 9.5, dump() frequently results in exhausted memory because of recursion. To work around this, you can loop through _context to see all the keys in it:
<ol>
{% for key, value in _context %}
<li>{{ key }}</li>
{% endfor %}
</ol>
Then use a conditional to check (for example {% if loop.index == 2 %}
), and dump that value only if necessary.
Within version 9.5 and later, dump() is a wrapper for Symfony vardumper, and does not have this issue.
Debugging with xdebug
The most often recommended way to debug is to use an IDE with an xdebug plugin.
The simplest configuration to setup is to use PHPstorm (commercial) and xdebug. Microsoft's VSCode is a free open-source IDE with plugins that will do the same but do not require you to buy commercial software.
Using xdebug will allow you to step through the process, view the variable contents, and do so in a way that eliminates the mysteries under the covers, as well as preventing the infinite loops that may arise when using dump or kint.
A helpful little module called twig_xdebug may help in showing available variables in with xdebug.
Debugging with kint
An alternative to dump()
is kint, a PHP debugging tool. The kint()
function works exactly same as the dump()
function above, but provides an expandable/collapsible interface to the variables that it prints out.
Kint used to be included in the devel project but that is no longer the case. However, you will use Devel to configure Kint as your "Variables Dumper" of choice.
- Download the devel module and install it. (See also Downloading and Installing a Module from Drupal.org.)
- From the root of your project (where your site's composer.json lives), install the
kint-php
library using Composer withcomposer require kint-php/kint --dev
. - Clear the cache. Using the Manage administrative menu, navigate to Configuration > Development > Performance (admin/config/development/performance) and select Clear all caches.
- Configure Kint as your "Variables Dumper" of choice. Using the Manage administrative menu, navigate to Configuration > Development > Devel settings (admin/config/development/devel) and under the heading, Variables Dumper, select Kint, then Save configuration.
- Like the
dump
function,kint()
will not display any output unless debugging is enabled. Learn how to enable Twig debugging. - In your .twig files, use
kint()
to inspect the variables just likedump()
is described above. - Optionally, download and install the Devel Kint Extras module to search the nested variable list.
If a default {{ kint() }}
breaks your page, you can add a max depth of the dump. By default Kint has a depth of 7 levels which can be - in some cases - too heavy to render. As from kint ^4 this can be adjusted by adding a depth limit in your settings(.local).php. Read more in this Github Gist:
// Change kint max_depth setting.
if (class_exists('Kint')) {
// Set the max_depth to prevent out-of-memory.
\Kint::$depth_limit = 4;
}
Method and class allowed policy
When working with objects, we've allowed calling certain set of getters and setters or objects through the TwigSandboxPolicy
class. This is done to prevent accidental methods from being called in your templates. For example: {{ node.delete }}
on the node object may delete the node if the allowed policy was not in place. You can extend the allowed policy by adding the following to your settings.php
$settings['twig_sandbox_allowed_methods'] = [
'id',
'label',
'bundle',
'get',
'__toString',
'toString',
'referencedEntities',
];
Where 'referencedEntities'
is the method you'd like to use in your template.
Debugging with console.log
We can add the following to a twig template and view the logs in the browser:
<script>console.log({{ _context | json_encode | raw}});</script>
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion