Symfony – Generating absolute urls

Generating absolute urls (including hostname and scheme (http / https) is super useful for including full urls in templates or email content (eg. when you want to pass on an address to someone which is getting your emails!)

How?

In templates;

{{ absolute_url(path('route_name', {...})) }}

In controllers;

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;


$url = $this->generate(
'app_default_index',
['name' => 'Steve'], UrlGeneratorInterface::ABSOLUTE_URL
);

In services;

First import the class name for the url generator, and instance of the generator;

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/** @var UrlGeneratorInterface */
protected $urlGenerator;

/**
 * Inject URL Generator as a service
 * @param UrlGeneratorInterface $urlGenerator
 * @required
 */
public function setUrlGeneratorService(UrlGeneratorInterface $urlGenerator) {
    $this->urlGenerator = $urlGenerator;
}

Then, inside your method (in the service);

$url = $this->urlGenerator->generate(
'app_default_index',
['name' => 'Steve'], UrlGeneratorInterface::ABSOLUTE_URL
);

Leave a Reply