Skip to content

Instantly share code, notes, and snippets.

@gwagroves
Last active April 7, 2024 13:02
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gwagroves/58156593ef87c815d4bed6a86f0bf370 to your computer and use it in GitHub Desktop.
Save gwagroves/58156593ef87c815d4bed6a86f0bf370 to your computer and use it in GitHub Desktop.
Drupal 8 Paragraphs: Add a theme suggestion based on the paragraph and the type of the parent node / entity.
<?php
/**
* Implements theme_suggestions_HOOK_alter().
*/
function mytheme_theme_suggestions_paragraph_alter(array &$suggestions, array $variables) {
/** @var \Drupal\paragraphs\ParagraphInterface $paragraph */
$paragraph = $variables['elements']['#paragraph'];
/** @var \Drupal\Core\Entity\ContentEntityInterface $parent */
$parent = $paragraph->getParentEntity();
$suggestions[] = 'paragraph__' . $paragraph->bundle() . '__' . $parent->bundle();
}
@adamfchs
Copy link

This was awesome for helping me to figure out how to get specific templates for individual paragraph items (so I can create a custom code widget). Thanks!

@therobyouknow
Copy link

Sorry - I have to ask, does this really work, @gwagroves, @adamfchs ?

I ask because the only forms of this function I can find elsewhere are:

mytheme_theme_suggestions_node_alter
mytheme_theme_suggestions_page_alter

not

mytheme_theme_suggestions_paragraph_alter

@tarto-dev
Copy link

@therobyouknow in fact, it implements theme_suggestions_HOOK_alter doc where HOOK is the hooked entity type

@macherif
Copy link

macherif commented May 4, 2020

I think it's better to consider the parent already included in $variables this way :

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mythme_theme_suggestions_paragraph_alter(&$suggestions, $variables) {
  $paragraph = $variables['elements']['#paragraph'];
  $suggestions[] = 'paragraph__' . $paragraph->bundle() . '__' . $paragraph->view_mode;
  $parent = $paragraph->getParentEntity();
  if ($parent) {
    $suggestions[] = 'paragraph__' . $parent->bundle() . '__' . $paragraph->bundle();
  }
}

@gwagroves
Copy link
Author

@macherif Good call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment