Do new routes require a static first portion?

Using mymodule.routing.yml, I can successfully create a custom route at /foo/{bar}/{baz}, but I cannot use /{bar}/{baz} or /{bar}/foo/{baz} as path for a route; they just return a 404 error.

Why? Is there any way to create a route for /{bar}/{baz} (with strict requirements for bar)?

I've read the entirety of the routing API and I can't seem to find any answers.

Answers 2

  • In the routing system you can't do this. What you can do is path aliasing.

    Inbound: /{bar}/foo/{baz} -> /foo/{bar}/{baz}

    Outbound: /foo/{bar}/{baz} -> /{bar}/foo/{baz}

    You need a pattern to apply a regular expression on the path inbound, so /{bar}/{baz} is only possible if the parameters themselves have a distinctive pattern.

    I didn't find a tutorial how to build a path processor, but you can use the PathProcessorFront class as example.

    Register both as tagged service in the .services.yml file for the module.

    services:
      path_processor_front:
        class: Drupal\Core\PathProcessor\PathProcessorFront
        tags:
          - { name: path_processor_inbound, priority: 200 }
          - { name: path_processor_outbound, priority: 200 }
        arguments: ['@config.factory']
    

  • See Routing System on Drupal.org.

    Path (required): The URL to the route, with a leading forward slash (e.g., path: '/book'). You can use dynamic properties by including them in curly braces. (e.g., path: '/node/{node}/outline'). These will be passed along as arguments via parameter converters to the controller/form (see below). Note that the first item of the path must not be dynamic. You can also define optional parameters at the end of your path (See 'Optional Parameters' on this page).

    I hope this is enough to understand that routes cannot start with a slug. It must be a static value.


Related Questions