Persist: to do good deeds, you must first sharpen your tools. There are also a lot of tips in Drupal topic development. Learning these skills will get twice the result with half the effort. Today we are introducing how to debug and print the variables in the Twig template! Oops, Drupal 8!
In the drupal 8 twig template, you can find most of the commonly used Template variables in the annotations. But what should I do when some modules or themes introduce new variables?
The Twig template provides a function called 'dump' to help you discover and check these variables.
There is a small premise to use the 'dump' function. You need to enable the debug mode of twig. About how to enable the debug mode of twig https://www.drupal.org/node/1903374.
Check a single variable
{Dump (title )}}
Easy!
Then I want to see all the variables. How can this problem be solved?
Find all variables
{Dump ()}}
Find the available key of the variable
{Dump (_ context | keys )}}
Global variables available in Twig
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.
_ 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 charset.
Reminder
If you want to view all the variables, but the 'dump' function consumes up the memory due to recursion or other reasons, you can handle it in the following ways:
<Ol>
{% For key, value in _ context %}
<Li >{{ key }}</li>
{% Endfor %}
</Ol>
Then, use a constraint to check these variables, such as {if loop. index = 2%}, so that you can find what you need!