2

In most entity templates like node.html.twig or paragraph.html.twig I do get two major variables, the render array variable {{ content }}, but also the entity object variable like {{ node }} or {{ paragraph }}. Usually they are passed down to Twig in template_preprocess_ENTITYTYPE via $variables['element']['#ENTITYTYPE'].

I'm looking an equivalent for this in field templates, e.g. if I can do {{ node.field_whatever.something }} in node.html.twig I also want the get the same thing by using {{ field.something }} in field.html.twig

I guess I need the FieldItemList in template_preprocess_field to achieve this, but I don't know how to get it there.

  • Looking at field.html.twig (api.drupal.org/api/drupal/…), it appears that you have access to {{ items }}, which will contain the field items. – Jaypan Aug 22 '18 at 10:14
  • {{ items }} is just a nested array containing the attributes object and a render array, but not the field object. – Hudri Aug 22 '18 at 10:22
  • Hmm, in that case it doesn't look like it's available by default. You may need to load it in a preprocess function. – Jaypan Aug 22 '18 at 10:24
  • You can access #item, #items and #object (parent entity of the field) in the template directly, in this topic you'll find a few examples: drupal.stackexchange.com/questions/185052/get-image-url-in-twig – 4k4 Aug 22 '18 at 14:34
2

The field template receives its values from the parent entities' view display build array. This build array doesn't contain separate keys for the original fields on their components build arrays.

But a field preprocess function receives enough information to extract them: The 'element' item contains an '#object' key that holds the original entity, and a '#field_name' key that holds the name of the field. (Which is also available in the template as field_name thanks to template_preprocess_field().)

If you'd like to access the original field, you could do something like:

$element = $variables['element'];
$field_item_list = $element['#object']->get($element['#field_name']);

Which should return an instance of a class that implements FieldItemListInterface (FieldItemList, EntityReferenceFieldItemList, ...).

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.