I'd like to create a menu item that has a dynamic variable in it, specifically the user's ID.

This is the content of the example.routing.yml file.

  path: '/user/{user}/example'
    _controller: '\Drupal\example\Controller\ExampleController::test'
    _title: 'Test'
    _permission: 'access content'
    user: ^[0-9]+

This is the content of the example.links.menu.yml file.

  title: Test Link
  parent: example.parent
  description: 'Test Link'
  route_name: example.test
  weight: 3
  route_parameters: {user: 5}

5 is the user ID. I'd like to pull it from the logged-in user.

Is this possible?

  • Create a second route that has no user parameter and when accessed redirects to the first route with the current user parameter inserted.
    – Eyal
    Oct 22, 2016 at 0:14
  • I would agree with what Eyal said. Specifically you could access the currently logged in user like this. <?php class ExampleController { public function getUserId() { $currentUser = User::load(\Drupal::currentUser()->id()); // redirect to the other route now that you've got the current user. } }
    – chap
    Oct 22, 2016 at 1:01

1 Answer 1


It isn't possible to put dynamic variables into a menu.links.yml file. However, you can create a menu links class and set route parameters in there. You need to specify the class in the yaml file.

  route: my_route
  class: Drupal\my_module\Plugin\Menu

You can also include the normal menu link stuff like the menu_name in the yaml file.

The class extends MenuLinkBase and requires the getTitle(), getDescription(), and updateLink() methods, but the method we're interested in is the getRouteParameters() method. Simply return an array with your route parameters and you're golden.

public function getRouteParameters() {
  return [
    'user' => $current_user->id(),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.