Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 62 ยท Routing and Controllers

Generating URLs

Learn to generate URLs from route names in Symfony with generateUrl, UrlGeneratorInterface and Twig path()/url(), including absolute URLs and query strings.

Routing works in two directions. Matching turns a URL into a controller. Generating turns a route name and some parameters back into a URL. You need the second direction everywhere: links in templates, redirects after a form, links in emails, sitemap entries and API responses that point to other resources.

The rule of the chapter is simple: never type a URL by hand; ask the router for it by name. If you later change /blog/{slug} to /articles/{slug}, every generated link follows automatically, and a typo in a route name fails loudly instead of producing a dead link. In this lesson you will generate URLs in controllers, services and Twig, learn the difference between paths and absolute URLs, and run a small URL generator to see what happens to extra parameters, defaults and mistakes.

flowchart LR
    A["Route name<br/>blog_show"] --> G["UrlGenerator"]
    B["Parameters<br/>slug=hello-world"] --> G
    T["Reference type<br/>path or absolute URL"] --> G
    X["Request context<br/>scheme, host, base URL"] --> G
    G --> U["/blog/hello-world<br/>or https://example.com/blog/hello-world"]

The generator combines a route name, parameters and the current request context to produce either a path or an absolute URL.

In controllers and services

A controller that extends AbstractController has a shortcut, generateUrl(). Plain services get the same ability by injecting UrlGeneratorInterface:

PHP
// real Symfony, read-only
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

// In a controller
$path = $this->generateUrl('blog_show', ['slug' => 'hello-world']);
// "/blog/hello-world"

$absolute = $this->generateUrl('blog_show', ['slug' => 'hello-world'], UrlGeneratorInterface::ABSOLUTE_URL);
// "https://example.com/blog/hello-world"

// In any service
final class SitemapBuilder
{
    public function __construct(private UrlGeneratorInterface $urlGenerator) {}

    public function entryFor(string $slug): string
    {
        return $this->urlGenerator->generate('blog_show', ['slug' => $slug], UrlGeneratorInterface::ABSOLUTE_URL);
    }
}

The most common companion is the redirect helper, which generates a URL and wraps it in a response in one step:

PHP
// real Symfony, read-only
return $this->redirectToRoute('blog_show', ['slug' => $post->getSlug()]);

In Twig

Templates use two functions with the same arguments: path() produces an absolute path, url() an absolute URL.

TWIG
{# real Symfony, read-only #}
<a href="{{ path('blog_show', {slug: post.slug}) }}">Read more</a>

{# page and sort are not placeholders, so they become a query string #}
<a href="{{ path('blog_list', {page: 2, sort: 'new'}) }}">Next</a>

{# use url() where the link leaves your site: emails, RSS, social cards #}
<link rel="canonical" href="{{ url('blog_show', {slug: post.slug}) }}">

The second link renders as /blog/2?sort=new when the route is /blog/{page}. That leads to the rule for parameters.

What happens to parameters

  1. Placeholder parameters are inserted into the path, and the value is URL-encoded, so a slash or space in a value cannot break the structure.
  2. Extra parameters that are not placeholders are appended as a query string.
  3. Missing mandatory parameters throw MissingMandatoryParametersException.
  4. A parameter that violates the route's requirement throws InvalidParameterException. A requirement protects both directions: /post/banana cannot be matched and cannot be generated.
  5. Defaults are used for missing optional placeholders, and a trailing optional placeholder whose value equals its default is dropped from the URL.
  6. An unknown route name throws RouteNotFoundException.

Special parameters give you a few extras: _locale picks the locale for localized routes, and _fragment appends #anchor to the URL:

PHP
// real Symfony, read-only
$this->generateUrl('blog_show', ['slug' => 'hello-world', '_fragment' => 'comments']);
// "/blog/hello-world#comments"

Reference types

The third argument of generate() chooses what comes back:

Constant Result Typical use
ABSOLUTE_PATH (default) /blog/hello-world Links in your own pages
ABSOLUTE_URL https://example.com/blog/hello-world Emails, feeds, sitemaps, APIs
RELATIVE_PATH ../blog/hello-world Rare, mostly for static exports
NETWORK_PATH //example.com/blog/hello-world Scheme-relative links

The scheme, host and base URL of an absolute URL come from the request context, which Symfony fills from the current request. That works in the web but not on the command line, because there is no request. For commands, Messenger handlers and scheduled jobs, tell the router what your site's address is:

YAML
# config/packages/framework.yaml (real Symfony, read-only)
framework:
    router:
        default_uri: 'https://example.com'

Without default_uri, a URL generated in a console command would come out as http://localhost/..., which is a classic bug in "password reset" emails sent from queue workers.

A URL generator you can run

The stand-in below holds a route table and a generate() method with the same behaviour as the list above: encoding, query strings for extras, defaults, requirement checks and clear exceptions. It is a teaching model, not Symfony's code.

PHP A small URL generator (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the output line by line: the slug with a space, question mark and slash is encoded, the extra parameters became a query string, page 1 disappeared into the default, and the three mistakes each raised a different exception.

Why the request context matters

Here is the second part of the picture: the same route yields different absolute URLs depending on the context. A site installed in a subdirectory has a base URL (for example /shop) that is part of every generated path, and a command-line job has no request at all, so the context has to come from configuration. The next stand-in mimics Twig's path() and url() calls inside a template and renders it in four contexts.

PHP path() and url() depend on the context (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last context is the dangerous one: if a worker renders an email without a configured default URI, the links point at localhost. Setting default_uri is the fix.

Debugging with the console

When a link is wrong, ask the router instead of guessing:

Terminal
# real Symfony, read-only
php bin/console debug:router                 # all routes with name, method and path
php bin/console debug:router blog_show       # path, requirements, defaults of one route
php bin/console router:match /blog/hello     # which route handles this URL

debug:router shows the final path of each route after class prefixes and priority are applied, which is exactly what generate() will use.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you generate URLs from route names instead of writing them by hand?

    Generating from names keeps links in sync with the route table and surfaces mistakes as exceptions.
  2. 2. A route is /blog/{slug}. What does path('blog_show', {slug: 'x', page: 2}) produce?

    Placeholder values go into the path; parameters that are not placeholders become the query string.
  3. 3. Which function or constant gives you a full URL including scheme and host?

    url() and ABSOLUTE_URL include the scheme and host. path() and ABSOLUTE_PATH return only the path.
  4. 4. Emails sent from a Messenger worker contain http://localhost links. What is the usual fix?

    There is no request in a worker, so the router needs default_uri to know the scheme and host of your site.

Summary

  • Generate links with generateUrl(), UrlGeneratorInterface or Twig path()/url(), always by route name.
  • Placeholder values fill the path and are encoded; extra parameters become the query string; _fragment adds an anchor.
  • Missing, invalid or unknown parameters and routes throw dedicated exceptions.
  • ABSOLUTE_PATH is the default; use ABSOLUTE_URL for emails, feeds and sitemaps.
  • In console commands and workers, configure framework.router.default_uri, and use debug:router to inspect routes.

Next up: Controllers in Depth.