尝试使用hook_preprocess_menu突出显示Drupal 8中的当前菜单项

时间:2015-06-03 15:59:30

标签: php drupal-8

我有以下功能来创建主动跟踪功能。所以,如果我有/博客作为"父母"以及/ blog / mypost的帖子,当在mypost上时,博客链接会显示为突出显示。我不想为所有博客帖子制作菜单项。问题是当打开缓存(不使用settings.local.php和调试关闭)时,getRequestUri在某些页面上没有变化。它似乎是根据页面缓存的。它在页面缓存关闭的情况下工作正常,但我希望能够使用缓存。有没有更好的方法来检查当前路径并应用活动类?

function mytheme_preprocess_menu(&$variables, $hook) {
  if($variables['theme_hook_original'] == 'menu__main'){
    $node = \Drupal::routeMatch()->getParameter('node');
    if($node){
      $current_path = \Drupal::request()->getRequestUri();
      $items = $variables['items'];
      foreach ($items as $key => $item) {
        // If current path starts with a part of another path i.e. a parent, set active to li.
        if (0 === strpos($current_path, $item['url']->toString())) {
          // Add active link.
          $variables['items'][$key]['attributes']['class'] .= ' menu-item--active-trail';
        }
      }
    }
  }
}

我也试过把它放到一个模块中试着看看我是否可以获得当前路径,然后在菜单中执行twig逻辑 - main.twig.html模板,但我遇到了同样的问题。

function highlight_menu_sections_template_preprocess_default_variables_alter(&$variables) {
  $variables['current_path'] = $_SERVER['REQUEST_URI'];
}

3 个答案:

答案 0 :(得分:2)

经过很长一段时间尝试各种各样的事情后,我找到了一个很好的模块来解决这个问题。安装和去,而不是配置,它只是工作:

https://www.drupal.org/project/menu_trail_by_path

D7和D8的稳定版本。

答案 1 :(得分:0)

我尝试将一个活动路径声明为自定义菜单块的一部分,即使这样,我声明的路径也会被缓存。假设它与“无法设置活动链接有关 - 如果需要更多控制,则覆盖服务”。 this changelog中的陈述,但为什么MenuTreeParameters->setActiveTrail()存在是任何人的猜测。

对于好奇的(以及我以后搜索的时候!),这是我的块的build()函数:

public function build() {
  $menu_tree = \Drupal::menuTree();
  $parameters = new MenuTreeParameters();
  $parameters->setRoot('menu_link_content:700c69e6-785b-4db7-be49-73188b47b5a3')->setMinDepth(1)->setMaxDepth(1)->onlyEnabledLinks();

  // An array of routes and menu_link_content ids to set as active
  $define_active_mlid = array(
    'view.press_releases.page_1' => 385
  );
  $route_name = \Drupal::request()->get(RouteObjectInterface::ROUTE_NAME);
  if (array_key_exists($route_name, $define_active_mlid)) {
    $menu_link = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('id' => $define_active_mlid[$route_name]));
    $link = array_shift($menu_link);
    $parameters->setActiveTrail(array('menu_link_content:' . $link->uuid()));
  }

  $footer_tree = $menu_tree->load('footer', $parameters);
  $manipulators = array(
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree->transform($footer_tree, $manipulators);
  $menu = $menu_tree->build($tree);

  return array(
    'menu' => $menu,
  );
}

答案 2 :(得分:0)

[添加一个新的答案,因为这是一种完全不同于我之前的方法]

如果基于CSS的解决方案可以接受,这似乎没问题:

.page-node-type-press-release {
  a[data-drupal-link-system-path="press-room/press-releases"] {
    // active CSS styles here
  }
}