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 <my_theme>.theme
:
function customtheme_preprocess_node__dog(&$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?