Create new custom route

Our use case will be article authors pages. As we don’t want to have special route for every author - we need to create one witch will fit all our needs.

We need url like that: publisher.dev/authors/{authorSlug}. Author slug is a parameter passed to template and will be used by us for loading desired author. Example filled route: publisher.dev/authors/john-doe.

We can create route like that with API:

POST /api/v1/content/routes/

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{
    "route": {
        "name": "Authors",
        "slug": "authors",
        "type": "custom",
        "templateName": "author.html.twig",
        "variablePattern": "/{authorSlug}",
        "requirements": [
            {
                "key": "authorSlug",
                "value": "[a-zA-Z\\-_]+"
            }
        ]
    }
}

Important parts:

  • type custom: says to publisher that we want to set variablePattern and requirements manually.
  • variablePattern - string with set parameters placeholders added to end of route.
  • requirements = array of objects with regular expression for provided parameters.

Now in template author.html.twig we can load author by slug provided in url.

1
2
3
{% gimme author with { slug: app.request.attributes.get('authorSlug') } %}
    Author name: {{ author.name }}
{% endgimme %}

And done - you have custom route with option to pass parameters in url and use them later in template.