3 namespace Drupal\contextual\Element;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\Render\Element\RenderElement;
10 * Provides a contextual_links element.
12 * @RenderElement("contextual_links")
14 class ContextualLinks extends RenderElement {
19 public function getInfo() {
20 $class = get_class($this);
23 [$class, 'preRenderLinks'],
25 '#theme' => 'links__contextual',
27 '#attributes' => ['class' => ['contextual-links']],
30 'contextual/drupal.contextual-links',
37 * Pre-render callback: Builds a renderable array for contextual links.
39 * @param array $element
40 * A renderable array containing a #contextual_links property, which is a
41 * keyed array. Each key is the name of the group of contextual links to
42 * render (based on the 'group' key in the *.links.contextual.yml files for
43 * all enabled modules). The value contains an associative array containing
45 * - route_parameters: The route parameters passed to the url generator.
46 * - metadata: Any additional data needed in order to alter the link.
48 * array('#contextual_links' => array(
50 * 'route_parameters' => array('block' => 'system.menu-tools'),
53 * 'route_parameters' => array('menu' => 'tools'),
59 * A renderable array representing contextual links.
61 public static function preRenderLinks(array $element) {
62 // Retrieve contextual menu links.
65 $contextual_links_manager = static::contextualLinkManager();
67 foreach ($element['#contextual_links'] as $group => $args) {
69 'route_parameters' => [],
72 $items += $contextual_links_manager->getContextualLinksArrayByGroup($group, $args['route_parameters'], $args['metadata']);
75 // Transform contextual links into parameters suitable for links.html.twig.
77 foreach ($items as $class => $item) {
78 $class = Html::getClass($class);
80 'title' => $item['title'],
81 'url' => Url::fromRoute(isset($item['route_name']) ? $item['route_name'] : '', isset($item['route_parameters']) ? $item['route_parameters'] : [], $item['localized_options']),
84 $element['#links'] = $links;
86 // Allow modules to alter the renderable contextual links element.
87 static::moduleHandler()->alter('contextual_links_view', $element, $items);
89 // If there are no links, tell drupal_render() to abort rendering.
90 if (empty($element['#links'])) {
91 $element['#printed'] = TRUE;
98 * Wraps the contextual link manager.
100 * @return \Drupal\Core\Menu\ContextualLinkManager
102 protected static function contextualLinkManager() {
103 return \Drupal::service('plugin.manager.menu.contextual_link');
107 * Wraps the module handler.
109 * @return \Drupal\Core\Extension\ModuleHandlerInterface
111 protected static function moduleHandler() {
112 return \Drupal::moduleHandler();