The following snippets show you how to add hooks in order to generate twig files like mymodule/templates/my-entity--full.html.twig etc:

Theming a custom entity named "offer"

We can make the variables available by using the hook_theme(), template_preprocess_offer(), and offer_theme_suggestions_offer_alter hook in modules/custom/offer/offer.module. You need all three of them in order to work with twig files to customize your view modes with twig inside your module!

<?php

use Drupal\Core\Render\Element;

/**
* Provides a theme definition for custom content entity offer
* {@inheritdoc}
*/
function offer_theme($existing, $type, $theme, $path) {
  return [
    'offer' => [
      'render element' => 'elements',
    ],
    'offer__full' => [
      'base hook' => 'offer',
    ],
    'offer__teaser' => [
      'base hook' => 'offer'
    ],
  ];
}

/**
* Prepares variables for templates.
* implements hook_preprocess_HOOK()
*/
function template_preprocess_offer(array &$variables)
{
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

  $offer = $variables['elements']['#offer'];
  // The full offer object
  $variables['offer'] = $offer;

}

/**
* Adds template possibility for view modes
* Implements hook_provider_theme_suggestions_hook_alter
*/
function offer_theme_suggestions_offer_alter( array &$suggestions, array $vars, $hook ) {
  if ( $offer = $vars['elements']['#offer'] ) {
    if (isset($vars['elements']['#view_mode'])) {
      $suggestions[] = 'offer__' . $vars['elements']['#view_mode'];
    }
  }
}

Add a templates/offer--full.html.twig, templates/offer--teaser.html.twig and also a templates/offer.html.twig. The last is a fallback file for if you create a new view mode and there is no twig file available for that view mode.

Want to learn more?

These snippets were part of my video course Drupal 9 module development: introduction to custom entities.

 

 

Saved you some valuable time?

Received 100 so far from 4 kind contributors.