简体   繁体   中英

Drupal 8 - Show rendered paragraph field in node template

I have a content type called "Collection" which shows the properties of a tile collection. One of its fields is "Ambiences" and it's a paragraph with an image field, a text field and another subparagraph called "Tile breakdown" composed by an image, name, format and different display options.

Ambience
--Image
--Text
--Tile breakdown
----Image
----Name
----Format
----Container width
----[Other display options]

I need to render the "Ambience" images on one part of the node template and its "Tile breakdown" images on another part of the node template. All the images have been configured as colorbox with different image styles.

I would like to know, how can I show these images but in an already-rendered way, with all the colorbox stuff. I tried playing around with the preprocess function adding the paragraph to the $variables['content'] and using drupal_entity() from Twig Tweak but I was unable to make it work.

I also tried this but with the same luck.

Does anybody know how to do it?

Thanks in advance!

If you want to pull paragraph properties "up" into the node level, you'll have to do so in the template. You can make it easier with a preprocess function to extract the paragraph fields you want and add them as variables. Below is a an example where you collect all the tile's images into a variable array called ambiance_images, which you could then work with in your template. This is likely oversimplified structurally for what you need but should get you moving in the right direction. Note it assumes you've setup an image style (you should) and named it "tile".

function mytheme_preprocess_node(&$vars) {
  $node = $vars['node'];
  $type = $node->getType();
  $mode = $vars['view_mode'];

  if ($type == 'collection' && $mode == 'default') {
    $vars['ambiance_images'] = [];
    $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('tile');
    $tiles = $node->get('field_ambience')->referencedEntities()->first()->get('field_tiles')->referencedEntities();
    foreach ($tiles as $tile) {
      $vars['ambiance_images'][] = $style->buildUrl($tile->get('field_image')->entity->getFileUri());
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM