Pass custom variable to an entity reference templete i have the following problem in Drupal 8.

In custom content type there is a field, which is a multiple entity reference to the same content type. The field is set to use custom view mode, where only title and body fields are displayed. Kind of sub-pages structure. Also the content type has a boolean field, which determines whether the body field of sub pages (entity reference) should be displayed or not.
So in my theme_preprocess_field() hook i can get the boolean value, but i don't know how to pass it to the entity references, so in my node--mypage--grid-item.html.twig i could check for that flag and determine should be content.body be rendered or not.

Thank for any hints.
Create two view separate modes for your entity reference, one for each boolean value. In preprocessing, modify the view mode of the entity reference depending on the value of the boolean field.

This is a code example I'm using for paragraphs to change the view mode of a referenced media entity:

function mytheme_preprocess_paragraph__image(array &amp;$variables) {
  $paragraph = $variables['paragraph'];

  if ($paragraph-&gt;hasField('field_imageratio')) {
    $imageViewMode = str_replace('media.', '', $paragraph-&gt;field_imageratio-&gt;target_id);
    if (isset($variables['content']['field_image']['0']['#view_mode'])) {
      $variables['content']['field_image']['0']['#view_mode'] = $imageViewMode; 
    }
  }
}


I think you can largely reuse the logic above, field_imageratio should be replaced by your boolean field, field_image should be replaced by your entity reference field.