Browse Source

Add placeholder option to drupal_menu()

merge-requests/46/head
Dieter Holvoet 2 years ago
parent
commit
87bfa945f7
  1. 4
      src/TwigTweakExtension.php
  2. 54
      src/View/MenuViewBuilder.php

4
src/TwigTweakExtension.php

@ -209,8 +209,8 @@ class TwigTweakExtension extends AbstractExtension {
/**
* Returns the render array for Drupal menu.
*/
public static function drupalMenu(string $menu_name, int $level = 1, int $depth = 0, bool $expand = FALSE): array {
return \Drupal::service('twig_tweak.menu_view_builder')->build($menu_name, $level, $depth, $expand);
public static function drupalMenu(string $menu_name, int $level = 1, int $depth = 0, bool $expand = FALSE, bool $placeholder = FALSE): array {
return \Drupal::service('twig_tweak.menu_view_builder')->build($menu_name, $level, $depth, $expand, $placeholder);
}
/**

54
src/View/MenuViewBuilder.php

@ -2,12 +2,14 @@
namespace Drupal\twig_tweak\View;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Security\TrustedCallbackInterface;
/**
* Menu view builder.
*/
class MenuViewBuilder {
class MenuViewBuilder implements TrustedCallbackInterface {
/**
* The menu link tree service.
@ -40,7 +42,35 @@ class MenuViewBuilder {
*
* @see \Drupal\system\Plugin\Block\SystemMenuBlock::build()
*/
public function build(string $menu_name, int $level = 1, int $depth = 0, bool $expand = FALSE): array {
public function build(string $menu_name, int $level = 1, int $depth = 0, bool $expand = FALSE, bool $placeholder = FALSE): array {
$cache = [
'keys' => [
'twig_tweak_menu',
$menu_name,
'[level]=' . $level,
'[depth]=' . $depth,
'[expand]=' . (int) $expand,
],
'contexts' => [
'route.menu_active_trails:' . $menu_name,
],
'tags' => [
'config:system.menu.' . $menu_name,
]
];
if ($placeholder) {
return [
'menu' => [
'#lazy_builder' => [
'twig_tweak.menu_view_builder:build',
[$menu_name, $level, $depth, $expand, FALSE],
],
'#cache' => $cache,
],
];
}
$parameters = $this->menuLinkTree->getCurrentRouteMenuTreeParameters($menu_name);
// Adjust the menu tree parameters based on the block's configuration.
@ -66,19 +96,17 @@ class MenuViewBuilder {
$tree = $this->menuLinkTree->transform($tree, $manipulators);
$build = $this->menuLinkTree->build($tree);
if (!isset($build['#cache']['keys'])) {
$build['#cache']['keys'] = [
'twig_tweak_menu',
$menu_name,
'[level]=' . $level,
'[depth]=' . $depth,
'[expand]=' . (int) $expand,
];
}
$build['#cache']['contexts'][] = 'route.menu_active_trails:' . $menu_name;
$build['#cache']['keys'] = array_unique(array_merge($cache['keys'], $build['#cache']['keys'] ?? []));
$build['#cache']['contexts'] = Cache::mergeContexts($cache['contexts'], $build['#cache']['contexts'] ?? []);
$build['#cache']['tags'] = Cache::mergeTags($cache['tags'], $build['#cache']['tags'] ?? []);
return $build;
}
/**
* {@inheritdoc}
*/
public static function trustedCallbacks(): array {
return ['build'];
}
}

Loading…
Cancel
Save