Add theming suggestions to Custom Entities

Last updated on 06/09/2017

Having a custom entity entityname in a module called mymodule

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'entityname' => [
      'render element' => 'elements',
    ],
  ];
}
 
/**
 * Prepares variables for entityname entity templates.
 */
function template_preprocess_entityname(&$variables) {
  // Helpful $content variable for templates.
  $variables['entityname'] = [];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['entityname'][$key] = $variables['elements'][$key];
  }
}
 
/**
 * Implements hook_theme_suggestions_HOOK().
 *
 * Adds entityname template suggestions per view mode.
 */
function mymodule_theme_suggestions_entityname(array $variables) {
  $suggestions = [];
 
  /** @var Quiz $quiz */
  $quiz = $variables['elements']['#quiz'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
 
  $suggestions[] = 'entityname__' . $quiz->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'entityname__' . $quiz->id() . '__' . $sanitized_view_mode;
 
  return $suggestions;
}