Skip to main content

How to access a Paragaph module's field entity within node.html.twig.

Loading a paragraph field entity for use within node.html.twig.

In order to load a field in a paragraph referenced entity, we need to first load the referenced entities

  1. $my_paragraphs = $variables['node']->my_paragraph_field_name->referencedEntities();

Then, we look through the paragraphs to get the correct language, and in turn, pull the field from the paragraph.

  1.     foreach ($my_paragraphs as $paragraph) {
  2.       // Remember to check if translation exists
  3.       if ($stock->hasTranslation($variables['node']->language()->getId())) {
  4.         $paragraph = $paragraph->getTranslation($variables['node']->language()->getId());
  5.       }
  6.       $url = $paragraph->get('the_retrieved_field_from_the_paragraph')->getValue(); 
  7.     }

The full option within my preprocess_node function to pull a url that was living in a paragraph's entity reference.

  1. /**
  2.  * Implements template_preprocess_node().
  3.  */
  4. function MYTHEME_preprocess_node(&$variables) {
  5.   if ($variables['view_mode'] == 'VIEW_MODE' && $variables['node']->bundle() == 'NODE_TYPE') {
  6.     // Paragraphs/referencedEntities
  7.     $paragraphs = $variables['node']->MY_REFERENCED_PARAGRAPH_FIELD->referencedEntities();
  8.  
  9.     foreach ($paragraphs as $paragraph) {
  10.       // Remember to check if translation exists
  11.       if ($paragraph->hasTranslation($variables['node']->language()->getId())) {
  12.         $paragraph = $paragraph->getTranslation($variables['node']->language()->getId());
  13.       }
  14.       $url = $paragraph->get('MY_LINK_FIELD_IN_THE_PARAGRAPH')->getValue(); 
  15.     }
  16.  
  17.     if (!empty($url)) {
  18.       $variables['new_url'] = Url::fromUri($url[0]['uri']);
  19.     }
  20.   }
  21. }

Once that code is within the preprocess function, we can then output the URL in our node.twig.html file with: {{ new_url }}


Comments