While theming in Drupal, we will be working with both simple and complex variables consisting of PHP arrays that contain multiple values. Knowing that there can be multiple values, it is sometimes useful to dump the contents of the variable to know exactly what we are working with. The {{ dump() }} function allows us to view information about a template variable and is only available to us when Twig debugging is turned on. Let's take our name variable for instance and dump the contents to see what it contains.
Open page.html.twig and add the following to the bottom of the template:
{# Dumping variables #} {{ dump(name) }}
If we save our template and refresh the browser, we will now see the name variable being dumped to the page, displaying some additional info about our variable.
Using the dump() function, we can introspect more than one variable at a time by passing multiple arguments. Let's try this by adding an additional Drupal variable named is_front, as shown in the following code sample:
{# Dumping variables #} <pre>{{ dump(name, is_front) }}</pre>
If we save our template and refresh the browser, we will now see the is_front variable being dumped to the page as well as displaying whether we are on the front page of our site.
We can also discover all variables available to us within a Twig template by using a filter with our dump() tag. For instance, if we want to see everything available within the page.html.twig template for the page variable, we can add the following code:
{# Dumping keys #} <pre>{{ dump(page|keys) }}</pre>
The result will be a list of all the variables available for us to use to print out content provided to the page.html.twig template. This process will become very useful when working with other Twig templates.
By now, we should be comfortable working with a Twig template and variables. However, we can do much more with Twig than just print variables. We can also apply filters to variables to achieve a different functionality.