Drupal – Custom Twig template suggestions
     发布在:PHP      浏览:20      评论:0 条评论

用过 Drupal 的应该都知道,本地开发的时候,每个 Block、Menu 等元素都会有对应的 Twig Template 文件,并且有使用优先级。

但是,这些 Tempalte 名称都是系统默认提供的,有时候我们需要自定义一些 Template 来实现自定义的一些样式功能。

通过 hook_theme_suggestions_HOOK_alter 即可实现需要的功能。

Block

/**
 * Implements hook_theme_suggestions_block_alter().
 */
function demo_theme_suggestions_block_alter(array &$suggestions, array &$variables) {
    $elements = $variables['elements'];
    $content = $elemetns['content'];
    $id = $elemetns['#id'] ?? '';
    // Block suggestions for custom block bundles.
    if (isset($content['#block_content'])) {
        $bundle = $content['#block_content']->bundle();
        $view_mode = $content['#view_mode'];
        array_splice($suggestions, 1, 0, 'block__bundle__' . $bundle . '__view_mode__' . $view_mode);
        array_splice($suggestions, 1, 0, 'block__bundle__' . $bundle);
    }
    if ($id == 'mainnavigation') {
        $block = Block::load($elements['id']);
        $suggestions[] = 'block__' . $block->getRegion();
        $suggestions[] = 'block__' . $block->getRegion() . '__' . $elements['#id'];
    }
}

Menu

/**
 * Implements hook_theme_suggestions_menu_alter().
 */
function mhi_theme_suggestions_menu_alter(array &$suggestions, array &$variables) {
  $name = $variables['menu_name'];

  if ($name == 'main') {
    if (isset($variables['attributes']['block'])) {
      $hook = str_replace(['block-', '-'], ['', '_'], $variables['attributes']['block']);
      $suggestions[] = $variables['theme_hook_original'] . '__' . $hook;
    }

    if (isset($variables['view_mode'])) {
      $suggestions[] = $variables['theme_hook_original'] . '__' . $variables['view_mode'];
    }
  }
}
Responses