Drupal - How do I use variables in links.task.yml?

In your module_name.links.task.yml file you can add a route_parameters: array that lists the parameters you want to pass, in your case it would end up:

entity.node.check_backend:
  route_name: module_name.my_route
  base_route: entity.node.canonical
  title: My title
  route_parameters:
    arg1:  'value_for_arg1'

You can find this by looking at the code in \Drupal\Core\Menu\LocalTaskManager which parses this file.


You can use a class to generate dynamic tabs, and take example on the core tracker module which supports this.

Let's take a look in the tracker.links.task.yml file :

tracker.users_recent_tab:
route_name: tracker.users_recent_content
title: 'My recent content'
base_route: tracker.page
class: '\Drupal\tracker\Plugin\Menu\UserTrackerTab'

And then the \Drupal\tracker\Plugin\Menu\UserTrackerTab class :

<?php

namespace Drupal\tracker\Plugin\Menu;

use Drupal\Core\Menu\LocalTaskDefault;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Provides route parameters needed to link to the current user tracker tab.
 */
class UserTrackerTab extends LocalTaskDefault {

  /**
   * Current user object.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * Gets the current active user.
   *
   * @todo: https://www.drupal.org/node/2105123 put this method in
   *   \Drupal\Core\Plugin\PluginBase instead.
   *
   * @return \Drupal\Core\Session\AccountInterface
   */
  protected function currentUser() {
    if (!$this->currentUser) {
      $this->currentUser = \Drupal::currentUser();
    }
    return $this->currentUser;
  }


  /**
   * {@inheritdoc}
   */
  public function getRouteParameters(RouteMatchInterface $route_match) {
    return ['user' => $this->currentUser()->Id()];
  }

}

So you should create your own class like this one and implement the getRouteParameters method to return the array with the right parameters to be used. Simple like that :)

Reference to a well written article about this : https://medium.com/@joshirohit100/dynamic-tabs-in-drupal-8-8a76386e212c

Tags:

Routes

8