Add Theme Suggestions to Nested Paragraph Nodes

Public

Came across an issue where I needed to add a node template suggestion to the first referenced piece of content within a nested paragraph field. I also added template suggestions to the nested paragraph type.

Get raw version
php
  1. /**
  2.  * Implements hook_theme_suggestions_HOOK_alter().
  3.  */
  4. function TEMP_theme_suggestions_paragraph_alter(array &$suggestions, array &$variables) {
  5. $paragraph = $variables['elements']['#paragraph'];
  6. if ($paragraph->getType() == 'content_section') {
  7. $nested_paragraph = $paragraph->field_section_type->entity;
  8. $suggestions[] = 'paragraph__'.$paragraph->getType().'__'.$nested_paragraph->getType();
  9.  
  10. if ($nested_paragraph) {
  11. if (isset($nested_paragraph->field_content)) {
  12. $first = $nested_paragraph->field_content[0]->entity;
  13. $first->nested_suggestion = $nested_paragraph->getType().'__first';
  14. }
  15. }
  16. }
  17. }
  18.  
  19. /**
  20.  * Implements hook_theme_suggestions_HOOK_alter().
  21.  */
  22. function TEMP_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  23. $node = $variables['elements']['#node'];
  24. if (isset($node->nested_suggestion)) {
  25. $suggestions[] = 'node__'.$node->nested_suggestion;
  26. }
  27. }