4

I have a paragraph template where I print a field, for instance :

{{ content.field_products }}

In this template, I can get the paragraph id with :

paragraph.id()

I need to pass this paragraph id in the field template. What is the cleaner and simple way to do this ? I found a solution like this :

{{ content.field_products|merge({666:paragraph.id()}) }}

and then I get the value in field template like this :

{% set paragraphId = items[items|length-1].content %}

But this is dirty and generate a warning "Message d'erreurUser error: "4" is an invalid render array key in Drupal\Core\Render\Element::children() (line 99 of core/lib/Drupal/Core/Render/Element.php)." that I can understand giving that it's a dirty hack and drupal try to render my "666" array.

I'm probably gonna get the array with "666" key I added in a preprocess_field(), create a new variable for the field template et delete this diabolic hack from $variables to remove the warning due to a tentative to render this fake array, but I guess there is a better way to do ? I want simply to pass a variable from a template to its child...

thanks !

1 Answer 1

4

The clean solution is template preprocessing: In yourtheme.theme create something like

function yourtheme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  $parentEntity = $element['#object'];
  //might be useful for if-clause: $variables['field_name'] and $variables['field_type']
  if ($parentEntity && $parentEntity->getEntityTypeId() == 'paragraph' ) {
    //whatever logic you need goes here, e.g. something like
    //$variables['attributes']['data-from-parent-paragraph'] = $parentEntity->getYourStuff();
  }
}
1
  • 2
    Yes, in preprocess this is easier to find, but once you know where to look you can do this in TWIG as well: {{ element['#object'].id }}
    – 4uk4
    Jan 17, 2018 at 12:36

Your Answer

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

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