3

I am trying to print an entity reference field (from paragraphs module) into a controller.
I learned from this ticket that you can use
{{ teacher.field_classrooms.entity.field_in_paragraph.value }} to get the value of one field from the entity, but what I really need is to print the whole entity not just one field from the entity.

I was hoping to do something like {{ teacher.field_classrooms.entity }} rather than {{ teacher.field_classrooms.entity.field_in_paragraph.value }} {{ teacher.field_classrooms.entity.field_different_in_paragraph.value }}.

2

You can do that by setting a variable in your controller or in template_preprocess_teacher in your .theme file, like:

function template_preprocess_teacher(array &$variables) {
  $classrooms = $variables['elements'][0]->get('field_classrooms')->referencedEntities(); //probably a bit different for paragraphs ..

  foreach($classrooms as $classroom) {
    $variables['classrooms'][] = \Drupal::entityTypeManager()->getViewBuilder($classroom->getEntityTypeId())->view($classroom, 'optional-view-mode');
  }
}

And then access it in twig like this:

{{ classrooms }}

If you're looking for a twig only solution use the twig_tweak module, then it comes down to this:

{% for field_in_paragraph in teacher.field_classrooms.entity %}
  {{ drupal_entity('classroom', field_in_paragraph.value, 'optional-view-mode') }}
{% endfor %}

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.