How can i get the absolute url of route with symfony

17,421

Solution 1

The last facultative parameter has to be true to generate absolute url:

$router->generate('project_sign_in', array(), true);

in twig:

{{ path('project_sign_in', {}, true) }}
{# or #}
{{ url('project_sign_in') }}

in controller:

$this->generateUrl('project_sign_in', array(), true );

EDIT: for symfony 4, see @Michael B. answer
UrlGenerator->generate('project_sign_in', [], UrlGenerator::ABSOLUTE_URL);

Solution 2

Using the Routing Component at version 4.0:

<?php
use Symfony\Component\Routing\Generator\UrlGenerator;

UrlGenerator->generate('project_sign_in', [], UrlGenerator::ABSOLUTE_URL);

Solution 3

In Symfony 5.0, if you are using Routing within a service:

namespace App\Service;

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
.
.
.
private $router;

public function __construct(UrlGeneratorInterface $router)
{
    $this->router = $router;
}

public function foo()
{
    $this->router->generate('bar', [], urlGeneratorInterface::ABSOLUTE_URL);
}
Share:
17,421
user2784013
Author by

user2784013

Updated on June 25, 2022

Comments

  • user2784013
    user2784013 almost 2 years

    I am using symfony and I want to get the url of a specific route , my route is like this

    project_sign_in:
        pattern:  /signin
        defaults: { _controller: ProjectContactBundle:User:signIn }
    

    i want to generate the url from this route so i can get

    localhost/app_dev.php/signin or {SERVER-ADDRESS}/app_dev/signin

    if I was browsing the server.

  • Ahmed Ali
    Ahmed Ali almost 4 years
    worked perfectly... @goto solutions did not work for me
  • Andreas
    Andreas over 3 years
    from symfony 4 on, please see @MiachalB's answer