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?

1 Answer 1


$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 }}.

  • Thank you @Berdir.. Inspecting the $variables array I saw that it already contains elements. Putting my data in it, is there no the risk to overwrite by mistake some element required internally by Drupal?
    – Andrea
    Apr 21, 2016 at 7:49
  • Well, of course there is if you don't check what's already in there. Use safe names, e.g. prefixed with your module or theme.
    – Berdir
    Apr 21, 2016 at 8:13
  • Ok. I will go with prefixed names.
    – Andrea
    Apr 21, 2016 at 8:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.