I am using a preprocess function to get data from specific content types. I am able to print the data in the pre-process function but unable to view the same in the twig file.

This is the code I am using.

    function themename_preprocess_node__custom_content_type_name(&$variables) {
      $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
      // Get all products node IDs.
      $nids = $query->condition('type', 'content_type_products')->execute();
      // Load all product nodes.
      $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
      // Pass them to node--custom-content-type-name.html.twig.
      $variables['products'] = $nodes;
     //echo "<pre>";
     //print_r($variables['products']); exit;

print_r($variables['products']) shows the content of $variables['products'], but the node--custom-content-type-name.html.twig file doesn't print anything for {{products}}.



You need to apply EntityViewBuilderInterface::viewMultiple before you can render the nodes in a twig template:

$variables['products'] = \Drupal::entityTypeManager()


{{ products }}

You can add a view mode to viewMultiple() as second argument, for example teaser.

| improve this answer | |
  • When I try the above code, it is displaying the view(HTML), but here I need variables/properties of each product. like products.field_image, products.field_text so I can use them in my already designed twig – Mann Apr 8 at 6:35
  • 1
    Then use a custom view mode for products and add a second template node--content-type-products--custom-view-mode.html.twig. – 4k4 Apr 8 at 6:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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