Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This course is archived!
This tutorial is built using Drupal 8.0. The fundamental concepts of Drupal 8 - like services & routing - are still valid, but newer versions of Drupal *do* have major differences.

Routing Wildcards

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

Routing is packed with cool little features, but the most common thing you'll see is the addition of wildcards. Add a /{count} to the end of the route's path:

dino_says:
path: /the/dino/says/{count}
... lines 3 - 7

Because this is surrounded with curly-braces, the route will now match /the/dino/says/*anything*,

As soon as you have a routing wildcard called count, you can suddenly have a $count argument in your controller function:

... lines 1 - 6
class RoarController
{
public function roar($count)
{
... lines 11 - 12
}
}

The value for for the {count} part in the URL is passed to the $count argument. Both the wildcard and the argument must have the same name.

Use $count to change our scary greeting: $roar = 'R'.str_repeat('0', $count).'AR!'. Pass this to the Response:

... lines 1 - 8
public function roar($count)
{
$roar = 'R'.str_repeat('O', $count).'AR!';
return new Response($roar);
}
... lines 14 - 15

We just changed the route configuration, so we need to rebuild the routing cache:

drupal router:rebuild

Once I do, the /the/dino/says page returns a 404! Ah! As soon as you add /{count} to the route path, the route only matches when something is passed there. We need /the/dino/says/*something*, anything but blank. There are ways to make the wildcard optional - check out the Symfony routing docs.

Add 10 to the end of the URL:

http://localhost:8000/the/dino/says/10

Rooooooooooar! Make it 50 and the rooooooooooo....oooooooar gets longer.

Woah! You now know half of the new stuff in Drupal 8. It's this routing/controller layer. Make a route, then a controller and make that controller return a Response. Seriously, can we go on vacation now?

Leave a comment!

0
Login or Register to join the conversation
Cat in space

"Houston: no signs of life"
Start the conversation!

This tutorial is built using Drupal 8.0. The fundamental concepts of Drupal 8 - like services & routing - are still valid, but newer versions of Drupal *do* have major differences.

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "composer/installers": "^1.0.21", // v1.0.21
        "wikimedia/composer-merge-plugin": "^1.3.0" // dev-master
    }
}
userVoice