I have a custom content entity called 'offer'.

I've added template_preprocess_offer() and offer_theme() to the offer.module file.

function offer_theme($existing, $type, $theme, $path) {
  return [
    'offer' => [
      'render element' => 'elements',
    ],
  ];
}

function template_preprocess_offer(array &$variables) {
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

In modules/custom/offer/templates/offer.twig.html, I successfully render the entity.

Next, I've added theme suggestions because I've added a view mode 'full' via the UI.

/**
 * 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'];
    }
  }
}

After clearing caches:

<!-- THEME DEBUG --> <!-- THEME HOOK: 'offer' --> <!-- FILE NAME SUGGESTIONS: * offer--full.html.twig x offer.html.twig --> <!-- BEGIN OUTPUT from 'modules/custom/offer/templates/offer.html.twig' -->

This only works if I place a offer--full.html.twig inside the theme's templates folder. It doesn't work in the custom module template folder. Inside modules/custom/offer/templates, the template file with the view mode won't get used. While the template suggestions suggests offer--full.html.twig, offer.html.twig is used instead.

Why does it happen? How can I solve it?

Edit: I'm on drupal 9. My custom entity has no bundles. I've made sure the id inside @ContentEntityType is "offer".

有帮助吗?

解决方案

To make a theme suggestion work in the module folder you need an additional theme hook:

function offer_theme($existing, $type, $theme, $path) {
  return [
    'offer' => [
      'render element' => 'elements',
    ],
    'offer__full' => [
      'base hook' => 'offer',
    ],
  ];
}

其他提示

This only works if I place a offer--full.html.twig inside the theme's templates folder.

It doesn't work on the custom module. Inside modules/custom/offer/templates.

My guess, it's because you're using _alter.

Since this is your module, you don't need to alter it. Instead use hook_theme_suggestions_HOOK().

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function offer_theme_suggestions_offer(array $variables) {
  $suggestions = [];
  $offer = $variables['elements']['#offer'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'offer__' . $sanitized_view_mode;

  return $suggestions;
}
许可以下: CC-BY-SA归因
scroll top