Tips for using Kint in Drupal Twig development
I’d always known about Kint, but I’d never really used it until recently. The standard
dump(thing_to_dump) command was good enough, but a conversation on the Drupal Twig Slack channel reminded me that Kint shows available methods on an object, and that was good enough to prompt me to switch.
Kint is a ‘more powerful and modern PHP debugging tool’ which is really useful in Twig development for seeing what is available for printing, and what methods are available to call.
You can use it to quickly put together advanced Twig, for example this line which loads a entity reference field from a Drupal node, accesses a link field on the referenced entity (a taxonomy term), grabs the URI stored by the link field, and renders to a URL as a string:
(Note that the
|field_target_entity filter comes from the Twig Field Value contributed module)
Here are two tips that might save you a bit of wasted time when you switch over to using Kint.
Set a maximum number of levels for Kint to recurse through objects and references
Put this in your
settings.local.php file, or you’ll quickly run into out-of-memory PHP errors:
Be careful of the + button
Clicking Kint’s [+] button to open up the widget will result in your browser hanging and possibly crashing as Kint expands every possible level of its widget. A safer, but less intuitive method to open the widget is to click on the text instead of the button. This will open the widget, but without expanding each level.