Accessing the referencing / parent element in twig (paragraphs)

7.6k Views Asked by At

I have an entity reference field inside a (parent-)paragraph, which references multiple child-paragraphs.

Is it possible to access field values of the referencing paragraph in the children's (referenced paragraph's) twig templates?

Actually I'm just trying to count the total referenced items within one of the referenced item's twig templates itself. So I want to count its siblings + 1, if you want.

I'm aware of the fact that I could preprocess this in a module, but I would like to know if this is possible in twig.

3

There are 3 best solutions below

0
Stef Van Looveren On BEST ANSWER

In twig:

{% set paragraph_parent = paragraph.getParentEntity() %}
{% set width = paragraph_parent.field_width.0.value %}

<div class="{{ width }}">{{ content.field_images }}</div>
3
c1u31355 On

Since there is no response to this question I have to assume that this is not possible in Twig, but wanted to quick share the mentioned workaround via module...

getParentEntity()

is your friend.

A short example for making the referenced element's count available...

/* implements hook_preprocess_paragraph() (paragraph type product_teaser) */
function mymodule_preprocess_paragraph__product_teaser(&$variables) {

  /* makes paragraph siblings count (+ 1/self) available to template */
  $siblings_total = 1;      

  $paragraph = $variables['paragraph'];
  $parent_paragraph = $paragraph->getParentEntity();  

  if ( ( isset($parent_paragraph) ) && ( $parent_paragraph->hasField('field_paragraph_reference') ) ) {

    $field_content = $parent_paragraph->get('field_paragraph_reference')->getValue();

    if ( isset($field_content[0]['target_id']) ) {
      $siblings_total = count($field_content);
    }

  }

  $variables['mymodule_theming_sources']['siblings_total'] = $siblings_total;

}
1
Thirsty Six On

Another method using twig with 2 simple lines. It works fine.

{% set parent = paragraph._referringItem.parent.parent.entity %}

{{ parent.title.value }}