How to pass computed data from Theme preprocess functions to Twig templates? My general problem is this: I need to compute some data from PHP, usually using Drupal APIs, then pass computed values to a Twig template (in order to showing it).

For example: I have a template named node--dog.html.twig and inside this template I need to show the total count of Dogs I have inside the website. To do this I will compute from PHP the total count, using the Drupal::entityQuery API. But then I have to pass this computed value to the Twig template.

I tried to use a theme's preprocess function inside the file &lt;my_theme&gt;.theme:

function customtheme_preprocess_node__dog(&amp;$variables) {
  //
}


From here I'm able to do all PHP computations, but I couldn't find any documentation explaining how to pass data to Twig views. Can I use the $variables object? Is there any drawbacks? Is there a better approach?
$variables is an array, not an object.

But yes, it's the one and only way to pass additional data to the template. Anything you put in there is available in the template then. $variables['hello'] = 'world'; can be printed with {{ hello }}.