xxxxxxxxxx
# config/routes.yaml
example_route:
path: /example
controller: App\Controller\ExampleController::exampleAction
/////////// Controller Code
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
// ...
$router = $this->container->get('router');
$url = $router->generate('example_route');
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ExampleController extends AbstractController
{
/**
* @Route("/example", name="example_route")
*/
public function exampleAction(): Response
{
// Generate URL using $this->generateUrl()
$url = $this->generateUrl('example_route');
// ...
}
}
// Twig Template
{# Generate path #}
{{ path('example_route') }}
{# Generate absolute URL #}
{{ url('example_route') }}
xxxxxxxxxx
// src/Command/SomeCommand.php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
// ...
class SomeCommand extends Command
{
public function __construct(private RouterInterface $router)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
// generate a URL with no route arguments
$signUpPage = $this->router->generate('sign_up');
// generate a URL with route arguments
$userProfilePage = $this->router->generate('user_profile', [
'username' => $user->getUserIdentifier(),
]);
// generated URLs are "absolute paths" by default. Pass a third optional
// argument to generate different URLs (e.g. an "absolute URL")
$signUpPage = $this->router->generate('sign_up', [], UrlGeneratorInterface::ABSOLUTE_URL);
// when a route is localized, Symfony uses by default the current request locale
// pass a different '_locale' value if you want to set the locale explicitly
$signUpPageInDutch = $this->router->generate('sign_up', ['_locale' => 'nl']);
// ...
}
}
xxxxxxxxxx
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Generator\UrlGenerator;
// Autowire the UrlGeneratorInterface in your service/controller
public function __construct(UrlGeneratorInterface $urlGenerator)
{
$this->urlGenerator = $urlGenerator;
}
// Inside a method
public function generateUrl()
{
// Generate a URL for a route
$url = $this->urlGenerator->generate('route_name');
echo $url;
}