March 22, 2018 Javier Eguiluz

The Symfony Routing component allows to define requirements and default values for route placeholders using the requirements and defaults options respectively.

For example, in the following route defined with PHP annotations, the page placeholder is restricted to only accept integers and its default value is 1 :

1 2 3 4 5 6 7 8 9 10 11 12 use Symfony\Component\Routing\Annotation\Route ; class BlogController extends Controller { /** * @Route("/blog/{page}", name="blog_list", requirements={"page"="\d+"}, defaults={"page"="1"}) */ public function list ( $page ) { // ... } }

This route config is a bit verbose for simple conditions. That's why in Symfony 4.1 you can inline the route requirements and default values in the placeholders. The previous example in Symfony 4.1 can look like this:

1 2 3 4 5 6 7 /** * @Route("/blog/{page<\d+>?1}", name="blog_list") */ public function list ( $page ) { // ... }

The new syntax is {placeholder-name<requirements>?defaults} , every part of it is optional and it works in all config formats (annotations, YAML and XML):

1 2 3 4 5 6 7 8 9 10 11 blog_list : # no requirements and no default value path : /blog/{page} # with requirements but no default value path : /blog/{page<\d+>} # no requirements but with a default value path : /blog/{page?1} # no requirements but with default value = null path : /blog/{page?} # with requirements and default value = null path : /blog/{page<.*>?}

You can inline the config for multiple placeholders in the same route, but if there are lots of placeholders or the conditions are complex, the resulting config may be less readable and you should probably revert to the previous syntax: