Last active
December 7, 2022 12:27
-
-
Save krisrobinson/2e45bd817d562c3c6bc0f377e079da89 to your computer and use it in GitHub Desktop.
Drupal 8 check paragraph bundles and print out view modes in node.hml.twig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\paragraphs\Entity\Paragraph; | |
/** | |
* Implements template_preprocess_node | |
* | |
* Add variables for paragraphs available to node templates | |
*/ | |
function CUSTOM_preprocess_node(&$variables) { | |
// Convenience Variables | |
$node = $variables['node']; | |
// Empty Paragraph Variables for node.html.twig | |
$section_image = []; | |
$section_video = []; | |
// Get $paragraph->bundle() types and assign variables if they exist | |
if (!empty($node->field_sections->getValue())) { | |
foreach ($node->field_sections->getValue() as $key => $value) { | |
$paragraph = FALSE; | |
if (!empty($value['entity'])) { | |
// Use that, we're probably previewing. | |
$paragraph = $value['entity']; | |
} | |
elseif (!empty($value['target_id'])) { | |
$paragraph = Paragraph::load($value['target_id']); | |
} | |
if (!empty($paragraph) && $paragraph instanceof Paragraph) { | |
$view_builder = \Drupal::entityManager()->getViewBuilder('paragraph'); | |
$array = $view_builder->view($paragraph); | |
$array['#cache']['tags'][] = 'node:' . $node->id(); | |
// Populate variable arrays | |
if ($paragraph->bundle() == 'section_image') { | |
$section_image[] = $array; | |
// optionally change the view_mode | |
foreach ($section_image as $key => $value) { | |
$section_image[$key]['#view_mode'] = 'teaser'; | |
} | |
} | |
if ($paragraph->bundle() == 'section_video') { | |
$section_video[] = $array; | |
// optionally change the view_mode | |
foreach ($section_video as $key => $value) { | |
$section_video[$key]['#view_mode'] = 'teaser'; | |
} | |
} | |
} | |
} | |
} | |
// Populated Variables | |
$variables['section_image'] = $section_image; | |
$variables['section_video'] = $section_video; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% if section_video %} | |
<p>this has a video!</p> | |
{% for video in section_video %} | |
{% if loop.first %} | |
{{ video }} | |
{% endif %} | |
{% endfor %} | |
{% elseif section_video is empty and section_image %} | |
<p>this has no video but it has an image!</p> | |
{% for image in section_image %} | |
{% if loop.first %} | |
{{ image }} | |
{% endif %} | |
{% endfor %} | |
{% else %} | |
<p>No media!</p> | |
{% endif %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment