Home > Net >  Symfony 6 - Routes with Attribute Annoation - How to pass route name via variable?
Symfony 6 - Routes with Attribute Annoation - How to pass route name via variable?

Time:04-08

I am currently working on a symfony 6 project and use the attribute annotation for the routes directly inside the controller.

Example:

#[Route('/new', name: 'country_new', methods: ['GET', 'POST'])]

Now I would like to pass a part of the name of the route via a variable like:

private $routeName = "country"; 
#[Route('/', name: $this->routeName.'_index', methods: ['GET'])]

However this is not working and I get the following error: "Compile Error: Constant expression contains invalid operations"

Do you have an idea if this is even possible and if so how I can achieve this?

CodePudding user response:

This is not specific to Symfony, actually, but to PHP attributes in general. Per the documentation:

Arguments to attributes can only be literal values or constant expressions

However, as it relates to Symfony, if you are looking to just prefix all of the routes in a given controller, you can put a Route attribute on the class itself, too.

  • Related