メニューリンクの兄弟を取得


11

現在のページの兄弟リンクであるDrupal 8でメニューを作成しようとしています。したがって、メニューが次の場合:

  • ホーム
  • 親1
    • サブペアレント1
      • 子供1
    • サブペアレント2
      • 子供2
      • 子供3
      • 子供4
  • 親2

「子3」ページを表示しているときに、次のようにリンクするメニューブロックが必要です。

  • 子供2
  • 子供3
  • 子供4

D7でこれを行う方法を知っていると思いますが、その知識をD8に変換するのに苦労しています。これはD8で実行可能なことですか?もしそうなら、それを行う方法について誰かが私を正しい方向に向けることができますか?

ありがとう!

明確化:異なる深さのメニュー項目が兄弟を表示できるように、子レベルを可変にする必要があります。したがって、たとえば、子供用のメニューが必要なことに加えて、私は副親用のメニューと親用のメニューなどが必要になります。また、メニューの深さや、すべてのセクションでその深さを制御したり、それについて理解したりすることはできません。

回答:


19

そのため、カスタムブロックを作成し、ビルドメソッドで、トランスフォーマーが追加されたメニューを出力することで、これを可能にするコードを見つけました。これは、ブロック内のメニューを取得し、それにトランスフォーマーを追加する方法を理解するために使用したリンクです:http : //alexrayu.com/blog/drupal-8-display-submenu-block。私build()はこのようになってしまいました:

$menu_tree = \Drupal::menuTree();
$menu_name = 'main';

// Build the typical default set of menu tree parameters.
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

// Load the tree based on this set of parameters.
$tree = $menu_tree->load($menu_name, $parameters);

// Transform the tree using the manipulators you want.
$manipulators = array(
  // Only show links that are accessible for the current user.
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  // Use the default sorting of menu links.
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  // Remove all links outside of siblings and active trail
  array('callable' => 'intranet.menu_transformers:removeInactiveTrail'),
);
$tree = $menu_tree->transform($tree, $manipulators);

// Finally, build a renderable array from the transformed tree.
$menu = $menu_tree->build($tree);

return array(
  '#markup' => \Drupal::service('renderer')->render($menu),
  '#cache' => array(
    'contexts' => array('url.path'),
  ),
);

トランスフォーマーはサービスであるためintranet.services.yml、最終的に定義したクラスを指すようにイントラネットモジュールにを追加しました。クラスには3つのメソッドがありました:removeInactiveTrail()getCurrentParent()、ユーザーが現在いるページの親を取得するために呼び出されstripChildren()、現在のメニュー項目とその兄弟の子のみにメニューを削除しました(つまり、存在しないすべてのサブメニューを削除しました)アクティブトレイルのt)。

これは次のようになります。

/**
 * Removes all link trails that are not siblings to the active trail.
 *
 * For a menu such as:
 * Parent 1
 *  - Child 1
 *  -- Child 2
 *  -- Child 3
 *  -- Child 4
 *  - Child 5
 * Parent 2
 *  - Child 6
 * with current page being Child 3, Parent 2, Child 6, and Child 5 would be
 * removed.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The menu link tree to manipulate.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
 *   The manipulated menu link tree.
 */
public function removeInactiveTrail(array $tree) {
  // Get the current item's parent ID
  $current_item_parent = IntranetMenuTransformers::getCurrentParent($tree);

  // Tree becomes the current item parent's children if the current item
  // parent is not empty. Otherwise, it's already the "parent's" children
  // since they are all top level links.
  if (!empty($current_item_parent)) {
    $tree = $current_item_parent->subtree;
  }

  // Strip children from everything but the current item, and strip children
  // from the current item's children.
  $tree = IntranetMenuTransformers::stripChildren($tree);

  // Return the tree.
  return $tree;
}

/**
 * Get the parent of the current active menu link, or return NULL if the
 * current active menu link is a top-level link.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The tree to pull the parent link out of.
 * @param \Drupal\Core\Menu\MenuLinkTreeElement|null $prev_parent
 *   The previous parent's parent, or NULL if no previous parent exists.
 * @param \Drupal\Core\Menu\MenuLinkTreeElement|null $parent
 *   The parent of the current active link, or NULL if not parent exists.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement|null
 *   The parent of the current active menu link, or NULL if no parent exists.
 */
private function getCurrentParent($tree, $prev_parent = NULL, $parent = NULL) {
  // Get active item
  foreach ($tree as $leaf) {
    if ($leaf->inActiveTrail) {
      $active_item = $leaf;
      break;
    }
  }

  // If the active item is set and has children
  if (!empty($active_item) && !empty($active_item->subtree)) {
    // run getCurrentParent with the parent ID as the $active_item ID.
    return IntranetMenuTransformers::getCurrentParent($active_item->subtree, $parent, $active_item);
  }

  // If the active item is not set, we know there was no active item on this
  // level therefore the active item parent is the previous level's parent
  if (empty($active_item)) {
    return $prev_parent;
  }

  // Otherwise, the current active item has no children to check, so it is
  // the bottommost and its parent is the correct parent.
  return $parent;
}


/**
 * Remove the children from all MenuLinkTreeElements that aren't active. If
 * it is active, remove its children's children.
 *
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The menu links to strip children from non-active leafs.
 *
 * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
 *   A menu tree with no children of non-active leafs.
 */
private function stripChildren($tree) {
  // For each item in the tree, if the item isn't active, strip its children
  // and return the tree.
  foreach ($tree as &$leaf) {
    // Check if active and if has children
    if ($leaf->inActiveTrail && !empty($leaf->subtree)) {
      // Then recurse on the children.
      $leaf->subtree = IntranetMenuTransformers::stripChildren($leaf->subtree);
    }
    // Otherwise, if not the active menu
    elseif (!$leaf->inActiveTrail) {
      // Otherwise, it's not active, so we don't want to display any children
      // so strip them.
      $leaf->subtree = array();
    }
  }

  return $tree;
}

これはそれを行うための最良の方法ですか?おそらく違います。しかし、それは少なくとも同様のことをする必要がある人々のための出発点を提供します。


これは、フッターマップが行うこととほぼ同じです。+1。menu.treeサービスを使用します。
mradcliffe 2016年

2
service.ymlファイルに配置する必要があるコードを教えていただけませんか?service.ymlファイルからクラスを指す方法は?
siddiq 2017

親のメニューリンクを除外する方法
Permana

3

Drupal 8のコアにはメニューブロック機能が組み込まれています。ブロックUiで新しいメニューブロックを作成して構成するだけです。

それは次のように起こります:

  • 新しいブロックを配置してから、ブロックを作成するメニューを選択します。
  • ブロック構成では、「初期メニューレベル」を3に選択する必要があります。
  • 3番目のレベルのメニュー項目のみを印刷する場合は、「表示するメニューレベルの最大数」を1に設定することもできます。

残念ながら、ページがどのレベルになるかわからないので、そのためのメニューブロックを作成することはできません。サイト構造が最終的に何であるかに応じて、可変レベルにする必要がある可能性もあります。
エリンマクラフリン

Drupal 8のmenu_blockには現在、現在のノードを追跡する機能は含まれていません。drupal.org/node/2756675
クリスチャン、

静的使用には問題ありません。ただし、「すべてのページにブロックを配置し、現在のレベルに関係なく現在のページの兄弟を表示する」のように動的に使用することはできません。
leymannx

3

現在のリンクにルートを設定すると、トリックが実行される場合があります。

$menu_tree = \Drupal::menuTree();
$menu_name = 'main';

$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
$currentLinkId = reset($parameters->activeTrail);
$parameters->setRoot($currentLinkId);
$tree = $menu_tree->load($menu_name, $parameters);

// Transform the tree using the manipulators you want.
$manipulators = array(
  // Only show links that are accessible for the current user.
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  // Use the default sorting of menu links.
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
);
$tree = $menu_tree->transform($tree, $manipulators);

いや、残念ながらこれは子供たちだけを示しています。しかし兄弟ではありません。OPは兄弟を必要としています。
leymannx

3

兄弟メニューブロック

@Icubesの回答により、MenuLinkTreeInterface::getCurrentRouteMenuTreeParameters現在のルートのアクティブなメニュートレイルを取得できます。これにより、親メニュー項目もあります。MenuTreeParameters::setRoot新しいツリーを構築するための開始点としてそれを設定すると、希望する兄弟メニューが表示されます。

// Enable url-wise caching.
$build = [
  '#cache' => [
    'contexts' => ['url'],
  ],
];

$menu_name = 'main';
$menu_tree = \Drupal::menuTree();

// This one will give us the active trail in *reverse order*.
// Our current active link always will be the first array element.
$parameters   = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
$active_trail = array_keys($parameters->activeTrail);

// But actually we need its parent.
// Except for <front>. Which has no parent.
$parent_link_id = isset($active_trail[1]) ? $active_trail[1] : $active_trail[0];

// Having the parent now we set it as starting point to build our custom
// tree.
$parameters->setRoot($parent_link_id);
$parameters->setMaxDepth(1);
$parameters->excludeRoot();
$tree = $menu_tree->load($menu_name, $parameters);

// Optional: Native sort and access checks.
$manipulators = [
  ['callable' => 'menu.default_tree_manipulators:checkNodeAccess'],
  ['callable' => 'menu.default_tree_manipulators:checkAccess'],
  ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
];
$tree = $menu_tree->transform($tree, $manipulators);

// Finally, build a renderable array.
$menu = $menu_tree->build($tree);

$build['#markup'] = \Drupal::service('renderer')->render($menu);

return $build;

このソリューションは魅力のように機能しました。:)
Pankaj Sachdeva
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.